🍃 MongoDB Tutorial

MongoDB Element Operators: $exists and $type Explained

Learn how to query MongoDB documents by field existence with $exists and by field data type with $type, including all BSON type aliases.

MongoDB Element Operators

Element operators let you query based on whether a field exists, or what data type it holds — useful when your documents don't all share the same shape.

Operator Description
$exists Matches documents that have (or don't have) the specified field
$type Matches documents where a field is a specific BSON type

$exists

true matches documents that have the field (with any value, including null). false matches documents that don't have the field at all.

db.employees.find({ doj: { $exists: true } })
// only documents where doj is present

db.employees.find({ doj: { $exists: false } })
// only documents where doj is missing

You can also use 1/0 instead of true/false — they behave identically.

$type

Selects documents where a field's value is an instance of a specific BSON type. Useful when a collection's data is inconsistent (e.g. some age fields are numbers, others accidentally strings).

db.collection.find({ field: { $type: <BSON type> } })
db.collection.find({ field: { $type: [ <type1>, <type2>, ... ] } })

Types can be specified by number or by alias — both work the same way:

db.employees.find({ empid: { $type: 'int' } })
db.employees.find({ empid: { $type: 16 } })

Aliases are case-sensitive — 'Int' throws an error, only 'int' works.

Common BSON Types

Type Number Alias
Double 1 "double"
String 2 "string"
Object 3 "object"
Array 4 "array"
Binary data 5 "binData"
ObjectId 7 "objectId"
Boolean 8 "bool"
Date 9 "date"
Null 10 "null"
Regular Expression 11 "regex"
JavaScript 13 "javascript"
32-bit integer 16 "int"
Timestamp 17 "timestamp"
64-bit integer 18 "long"
Decimal128 19 "decimal"
Min key -1 "minKey"
Max key 127 "maxKey"
db.employees.find({ name: { $type: 'string' } })

Common Errors & Troubleshooting

  • $exists: true matching a field that's set to null — $exists only checks presence, not whether the value is meaningful. A field explicitly set to null still "exists" and matches $exists: true.
  • Using the wrong-case alias with $type — BSON type aliases are lowercase and case-sensitive — $type: 'Int' throws an error, only $type: 'int' works.
  • Assuming $type catches every inconsistency — $type only tells you the type of what IS there; it won't catch a field that's simply missing (pair it with $exists if you need both checks).

Key Takeaways

  • $exists checks presence, not value — a field set to null still "exists".
  • $type is invaluable for cleaning up inconsistent data across documents.
  • Type aliases are lowercase and case-sensitive; numeric codes work identically.