Syntax error MongoDB query to select one field if the other is null and the first field if both are not null?

MongoDB query to select one field if the other is null and the first field if both are not null?



For this, use $ifNull operator

Let us first create a collection with documents −

> dbquerySelectDemoinsertOne({"Value1":10,"Value2":null});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefc0ceef71edecf6a1f6b6")
}
> dbquerySelectDemoinsertOne({"Value1":null,"Value2":30});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefc0d7ef71edecf6a1f6b7")
}
> dbquerySelectDemoinsertOne({"Value1":60,"Value2":40});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefc0e2ef71edecf6a1f6b8")
}

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

> dbquerySelectDemofind()pretty();

Output

{
   "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"),
   "Value1" : 10,
   "Value2" : null
}
{
   "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"),
   "Value1" : null,
   "Value2" : 30
}
{
   "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"),
   "Value1" : 60,
   "Value2" : 40
}

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

> dbquerySelectDemoaggregate([
   {
      $project: {
         "Value1": { "$ifNull": [ "$Value1", "$Value2" ] }
      }
   }
]);

Output

{ "_id" : ObjectId("5cefc0ceef71edecf6a1f6b6"), "Value1" : 10 }
{ "_id" : ObjectId("5cefc0d7ef71edecf6a1f6b7"), "Value1" : 30 }
{ "_id" : ObjectId("5cefc0e2ef71edecf6a1f6b8"), "Value1" : 60 }

Updated on: 2019-07-30T22:30:26+05:30

446 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements