Navigation

Query for Null or Missing Fields


Use the Select your language drop-down menu in the upper-right to set the language of the following examples.


Different query operators in MongoDB treat null values differently.

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

Important

Use BsonNull.Value with the MongoDB C# driver to query for null or missing fields in MongoDB.

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

You can run the operation in the web shell below:

You can run the operation in the web shell below:

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

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

The query returns both documents in the collection.

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

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

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

The following example queries for documents that do not contain a field. [1]

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

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

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

Tip
See also:

Reference documentation for the $type and $exists operators.

[1] Starting in MongoDB 4.2, users can no longer use the query filter $type: 0 as a synonym for $exists:false. To query for null or missing fields, see Query for Null or Missing Fields.
Give Feedback

Select your language