Querying null value in MongoDB?

MongoDBDatabaseBig Data Analytics

To query null value in MongoDB, use $ne operator. Let us first create a collection with documents −

> db.queryingNullDemo.insertOne(
...    {
...       "StudentName":"Larry",
...       "StudentDetails":
...       {
...          "StudentAge":21,
...          "StudentSubject":"MongoDB"
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd00bec588d4a6447b2e05f")
}
> db.queryingNullDemo.insertOne(
...    {
...       "StudentName":"Sam",
...       "StudentDetails":
...       {
...          "StudentAge":23,
...          "StudentSubject":null
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd00c00588d4a6447b2e060")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.queryingNullDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cd00bec588d4a6447b2e05f"),
   "StudentName" : "Larry",
   "StudentDetails" : {
      "StudentAge" : 21,
      "StudentSubject" : "MongoDB"
      }
}
{
   "_id" : ObjectId("5cd00c00588d4a6447b2e060"),
   "StudentName" : "Sam",
   "StudentDetails" : {
      "StudentAge" : 23,
      "StudentSubject" : null
   }
}

Following is how you can query for null −

> db.queryingNullDemo.find({'StudentDetails.StudentSubject': {$ne: null}});

This will produce the following output −

{ "_id" : ObjectId("5cd00bec588d4a6447b2e05f"), 
"StudentName" : "Larry", 
"StudentDetails" : { "StudentAge" : 21, "StudentSubject" : "MongoDB" } }
raja
Published on 22-May-2019 12:04:05
Advertisements