Querying Null and Missed Fields

If we observe the way of inserting the documents we may got some doubts like

  1. At any time We can add new fields while insertion ,means all the documents of a collection need not to have same no of fields as a result some documents will have some fields and others doesn't.
  2. We can pass null values to fields.
  • So How to find the documents having the specific fields
  • So How to find the fields having null values

>_ Querying Existence of Field

MongoDB provides $exists operator to check the existence of a field. we will use this in combination of (at the place of query) find() methods

Usage Syntax

{fieldname : { $exists: true/false } }

Assume these records are there in users collection
{ "_id" : ObjectId("5774c4b4fc520de27ab8745c"), "userid" : "Alex", }
{ "_id" : ObjectId("5774c4b4fc520de27ab8745d"), "userid" : "Andrew", "Age" : 25}
{ "_id" : ObjectId("5774c4b4fc520de27ab8745e"), "userid" : null, "Age" : 44}

>_ Find the users having age field



{ "_id" : ObjectId("5774c4b4fc520de27ab8745d"), "userid" :"Andrew", "Age" : 25}
{ "_id" : ObjectId("5774c4b4fc520de27ab8745e"), "userid" : null, "Age" :44}

>_ Querying NULL Values

To Query the null values MongoDB provides the $type operator. MongoDB stores the data in BSON format, In BSON datatypes null is a datatype with 10 type.

So we can query the null values as


>_Find the users having userid as 'null'



 { "_id" : ObjectId("5774c4b4fc520de27ab8745e"), "userid" :null, "Age" : 44}