Navigation

Query for Null or Missing Fields

Different query operators in MongoDB treat null values differently.

The examples on this page use the db.collection.find() method in the mongo shell to query for null values. The examples on this page use the inventory collection. To populate the inventory collection, run the following in the mongo shell:

db.inventory.insert([
   { _id: 1, item: null },
   { _id: 2 }
])

You can run the operation in the web shell below:

Equality Filter

The { item : null } query matches documents that either contain the item field whose value is null or that do not contain the item field.

For example, the following query returns both documents:

db.inventory.find( { item: null } )

Type Check

The { item : { $type: 10 } } query matches documents that contains the item field whose value is null only; i.e. the value of the item field is of BSON Type Null (i.e. 10) :

db.inventory.find( { item : { $type: 10 } } )

The query returns only the document where the item field has a null value.

Existence Check

The { item : { $exists: false } } query matches documents that do not contain the item field:

db.inventory.find( { item : { $exists: false } } )

The query returns only the document that does not contain the item field:

See also

The reference documentation for the $type and $exists operators.