Element operators ($exists $type)
Element operators test whether a field exists or what BSON type it has.
In this page:
Syntax
{ field: { $exists: true } }
{ field: { $type: "string" } }
Element operators ($exists $type)
{ field: { $exists: true } } matches documents that have the field, even when its value is null. { field: { $type: "string" } } matches by BSON type name or number. They are handy for spotting dirty data in flexible collections.
Note:
$exists: true still matches fields set to null.
Example: Element operators ($exists $type)
test> db.things.insertMany([{ _id: 1, v: "text" }, { _id: 2, v: 42 }, { _id: 3, v: null }, { _id: 4 }])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.things.find({ v: { $exists: true } }, { _id: 1 })
[ { _id: 1 }, { _id: 2 }, { _id: 3 } ]
test> db.things.find({ v: { $exists: false } }, { _id: 1 })
[ { _id: 4 } ]
test> db.things.find({ v: { $type: "string" } }, { _id: 1 })
[ { _id: 1 } ]
test> db.things.find({ v: null }, { _id: 1 })
[ { _id: 3 }, { _id: 4 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Treating $exists false as null
- Using JavaScript typeof names instead of BSON types
- Forgetting arrays match on element types
Chapter Summary
- $exists tests presence
- null values still exist
- $type tests BSON types
- Great for data quality checks
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: