Querying for the field that have null values stored in mongodb
Posted By : RAJAT KATIYAR | 28-Feb-2016
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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.