- MongoDB CRUD Operations >
- Query Documents >
- Query for Null or Missing Fields
Query for Null or Missing Fields¶
On this page
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 populate the users
collection
referenced in the examples, run the following in mongo
shell:
Equality Filter¶
The { name : null }
query matches documents that either
contain the name
field whose value is null
or that
do not contain the name
field.
Given the following query:
The query returns both documents:
If the query uses an index that is sparse,
however, then the query will only match null
values, not missing
fields.
Changed in version 2.6: If using the sparse index results in an incomplete result, MongoDB will not
use the index unless a hint()
explicitly specifies the
index. See Sparse Indexes for more information.
Type Check¶
The { name : { $type: 10 } }
query matches documents that
contains the name
field whose value is null
only;
i.e. the value of the name
field is of BSON Type Null
(i.e. 10
) :
The query returns only the document where the name
field has a
null
value: