MongoDB: How to query for records where field is null or not set?
If you want to ONLY count the documents with sent_at
defined with a value of null
(don't count the documents with sent_at
not set):
db.emails.count({sent_at: { $type: 10 }})
If the sent_at
field is not there when its not set then:
db.emails.count({sent_at: {$exists: false}})
If it's there and null, or not there at all:
db.emails.count({sent_at: null})
If it's there and null:
db.emails.count({sent_at: { $type: 10 }})
The Query for Null or Missing Fields section of the MongoDB manual describes how to query for null and missing values.
Equality Filter
The
{ item : null }
query matches documents that either contain the item field whose value isnull
or that do not contain theitem
field.db.inventory.find( { item: null } )
Existence Check
The following example queries for documents that do not contain a field.
The
{ item : { $exists: false } }
query matches documents that do not contain theitem
field:db.inventory.find( { item : { $exists: false } } )
Type Check
The
{ item : { $type: 10 } }
query matches only documents that contain theitem
field whose value isnull
; i.e. the value of the item field is of BSON TypeNull
(type number10
) :db.inventory.find( { item : { $type: 10 } } )