Querying for the field that have null values stored in mongodb

Posted By : RAJAT KATIYAR | 28-Feb-2016

Querying for the fields that have Null Value stored in MongoDB

MongoDb comprises of different types of query operators, which treat the null values in a different manner.

 

Let’s see an example:


Let there be a record stored in one of the collections in the mongo,

{    

     {    

id:””,

firstName: ‘John’

},

{    

id:””,

firstName: ‘Jack’,

lastName: null

}

}

Now for fetching the documents which contains the lastName as null, a general command:

 

db.collection.find({lastName:null})

 

will return both the documents.

 

Since the above command matches all the documents that either contains the lastName as null or that does not contain this field. However, if the index which has been queried is parsed, will only find the documents in which that field actually exists, not in which the field is missing.

            But in the results it is required to fetch the record which only contains the null field.

So for this, the command is:

It can be done by checking the type of the field,

 

db.collection.find({lastName: {type: 10}})

 

Now this query will return only the documents which contains the null values saved in the documents. The typecheck matches only those documents in which the field exists and with the null value.

Type 10 means the field is the type of BSON null.

 

THANKS

About Author

Author Image
RAJAT KATIYAR

Rajat Katiyar is a very bright web app developer, he has good knowledge of JAVA, C/C++, C#.NET. Apart from this he has interest in theater and sports.

Request for Proposal

Name is required

Comment is required

Sending message..