MongoDB query to select one field if the other is null?

MongoDBDatabaseBig Data Analytics

To select one field if the other is null, use $ifNull. Let us create a collection with documents −

> db.demo182.insertOne({"FirstName":"Chris","LastName":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398ea19e4f06af55199802")
}
> db.demo182.insertOne({"FirstName":null,"LastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398ead9e4f06af55199803")
}
>
> db.demo182.insertOne({"FirstName":"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e398ebf9e4f06af55199804")
}

Display all documents from a collection with the help of find() method −

> db.demo182.find();

This will produce the following output −

{ "_id" : ObjectId("5e398ea19e4f06af55199802"), "FirstName" : "Chris", "LastName" : null }
{ "_id" : ObjectId("5e398ead9e4f06af55199803"), "FirstName" : null, "LastName" : "Miller" }
{ "_id" : ObjectId("5e398ebf9e4f06af55199804"), "FirstName" : "John", "LastName" : "Smith" }

Following is the query to select one field if the other is null −

> db.demo182.aggregate([
...   {
...      $project: {
...         "item": 1,
...         "Result": { "$ifNull": [ "$FirstName", "$LastName" ] }
...      }
...   }
...])

This will produce the following output −

{ "_id" : ObjectId("5e398ea19e4f06af55199802"), "Result" : "Chris" }
{ "_id" : ObjectId("5e398ead9e4f06af55199803"), "Result" : "Miller" }
{ "_id" : ObjectId("5e398ebf9e4f06af55199804"), "Result" : "John" }
raja
Published on 27-Mar-2020 07:58:20
Advertisements