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

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



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" }
Updated on: 2020-03-27T07:58:40+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements