Add a boolean field true to returned objects, when a specified value is in array. For NULL
or other values, set false.


For this, use $ifNull. It evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. Let us first create a collection with documents −

> db.demo542.insertOne({"ListOfName":["Chris","David"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8cabc6ef4dcbee04fbbc17")
}
> db.demo542.insertOne({"ListOfName":null});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8cabc8ef4dcbee04fbbc18")
}
> db.demo542.insertOne({"ListOfName":["David"]});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8cabd3ef4dcbee04fbbc19")
}
> db.demo542.insertOne({"Name":"John"});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8cabdaef4dcbee04fbbc1a")
}

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

> db.demo542.find();

This will produce the following output −

{ "_id" : ObjectId("5e8cabc6ef4dcbee04fbbc17"), "ListOfName" : [ "Chris", "David" ] }
{ "_id" : ObjectId("5e8cabc8ef4dcbee04fbbc18"), "ListOfName" : null }
{ "_id" : ObjectId("5e8cabd3ef4dcbee04fbbc19"), "ListOfName" : [ "David" ] }
{ "_id" : ObjectId("5e8cabdaef4dcbee04fbbc1a"), "Name" : "John" }

Following is the query to check for specific value −

> var id = "David";
> db.demo542.aggregate([
...    {
...       "$project": {
...          "matched": {
...             "$eq": [
...                {
...                   "$size": {
...                      "$ifNull": [
...                         { "$setIntersection": [ "$ListOfName", [id] ] },
...                         []
...                      ]
...                   }
...                },
...                1
...             ]
...          }
...       }
...    }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e8cabc6ef4dcbee04fbbc17"), "matched" : true }
{ "_id" : ObjectId("5e8cabc8ef4dcbee04fbbc18"), "matched" : false }
{ "_id" : ObjectId("5e8cabd3ef4dcbee04fbbc19"), "matched" : true }
{ "_id" : ObjectId("5e8cabdaef4dcbee04fbbc1a"), "matched" : false }

Updated on: 14-May-2020

154 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements