0
0
MongodbHow-ToBeginner · 3 min read

How to Find Documents with Null Value in MongoDB

To find documents with a null value in MongoDB, use the find() method with a query like { field: null }. This matches documents where the field is either null or does not exist. To find only documents where the field is explicitly null, combine { field: null } with { field: { $exists: true } }.
📐

Syntax

Use the find() method with a query object specifying the field to check for null. The basic syntax is:

  • { field: null }: Finds documents where field is null or missing.
  • { field: { $exists: true } }: Ensures the field exists.
  • Combine both to find documents where the field is explicitly null.
mongodb
db.collection.find({ field: null })
db.collection.find({ field: { $exists: true, $eq: null } })
💻

Example

This example shows how to find documents where the status field is null. It also shows how to find documents where status is missing or null.

mongodb
use testdb

// Insert sample documents
db.orders.insertMany([
  { _id: 1, status: "shipped" },
  { _id: 2, status: null },
  { _id: 3 },
  { _id: 4, status: "pending" }
])

// Find documents where status is null or missing
print('Documents with status null or missing:')
db.orders.find({ status: null }).forEach(doc => printjson(doc))

// Find documents where status is explicitly null
print('\nDocuments with status explicitly null:')
db.orders.find({ status: { $exists: true, $eq: null } }).forEach(doc => printjson(doc))
Output
{ "_id" : 2, "status" : null } { "_id" : 3 } { "_id" : 2, "status" : null }
⚠️

Common Pitfalls

A common mistake is to use { field: null } expecting to find only documents where the field is null. However, this query also returns documents where the field does not exist. To avoid this, combine $exists: true with $eq: null.

Wrong way:

db.collection.find({ field: null })

This returns documents with field missing or null.

Right way:

db.collection.find({ field: { $exists: true, $eq: null } })

This returns only documents where field is explicitly null.

mongodb
/* Wrong: includes missing fields */
db.orders.find({ status: null })

/* Right: only null values */
db.orders.find({ status: { $exists: true, $eq: null } })
📊

Quick Reference

QueryDescription
{ field: null }Finds documents where field is null or missing
{ field: { $exists: true, $eq: null } }Finds documents where field is explicitly null
{ field: { $exists: false } }Finds documents where field does not exist

Key Takeaways

Use { field: null } to find documents where the field is null or missing.
Combine $exists: true with $eq: null to find only documents where the field is explicitly null.
Remember that { field: null } matches both null and missing fields.
Use $exists: false to find documents where the field does not exist.
Always test queries to confirm they return the expected documents.