All the above answers are amazing and correct. Just want to add one improvement on the answers which is using $type
.
Starting with MongoDB 3.2, you can avoid using 10
(as hardcoded literals reduce the code readability) and instead can simply use string aliases i.e. "null"
. So to summarize-
1. If you want to pick records where sent_at
exists and has the value null
db.emails.count({sent_at: { $type: 'null' }});
// or
// This reduces the code readability as your peer might not know
// that what is the meaning of value 10
db.emails.count({sent_at: { $type: 10 }});
2. If you want to pick records which has either sent_at: null
or sent_at
does not exist
// This will ensure both the conditions
db.emails.count({ sent_at: null })
3. If you only want records where sent_at
does not exist
db.emails.count({sent_at: { $exists: false }});
4. If you only want to pick sent_at
where the field exists and may have any value
db.emails.count({sent_at: { $exists: true }});
Remember, this will pull any document of emails
which has any value including null
, 0
, ''
, false
.