Query for Null or Missing Fields
On this page
You can query for null
or missing fields in MongoDB
using the following methods:
Your programming language's driver.
The MongoDB Atlas UI. To learn more, see Query for Null or Missing Fields with MongoDB Atlas.
➤ Use the Select your language drop-down menu in the upper-right to set the language of the following examples or select MongoDB Compass.
Different query operators in MongoDB treat null
values differently.
Equality Filter
The query returns both documents in the collection.
Type Check
The query returns only the document where the item
field has a
value of null
.
Existence Check
The following example queries for documents that do not contain a field. [1]
The query only returns the document that does not contain the
item
field.
[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. |
Query for Null or Missing Fields with MongoDB Atlas
The example in this section uses the sample training dataset. To learn how to load the sample dataset into your MongoDB Atlas deployment, see Load Sample Data.
To query for a null
or missing field in MongoDB Atlas, follow these steps:
Navigate to the collection.
In the Atlas UI, click Database in the sidebar.
For the database deployment that contains the sample data, click Browse Collections.
In the left navigation pane, select the
sample_training
database.Select the
companies
collection.
Specify a query filter document.
To find a document that contains a null
or missing value,
specify a query filter document
in the Filter field. A query filter document uses
query operators
to specify search conditions.
Different query operators in MongoDB treat null
values differently.
To apply a query filter, copying each of the following documents into the
Filter search bar and click Apply.
Use the following query filter to match documents that either contain a
description
field with a null
value or do not contain the
description
field:
{ description : null }
Use the following query filter to match only documents that contain
a description
field with a null
value. This filter specifies
that the value of the field must be BSON Type Null
(BSON Type 10):
{ description : { $type: 10 } }
Use the following query filter to match only documents that
do not contain the description
field. Only the document
that you inserted earlier should appear:
{ description : { $exists: false } }