← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 3 of 7

Element operators ($exists $type)

Element operators test whether a field exists or what BSON type it has.
Syntax
javascript
{ 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)

bash
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
  1. Treating $exists false as null
  2. Using JavaScript typeof names instead of BSON types
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.