How to Find Documents Where Field Exists in MongoDB
In MongoDB, use the
$exists operator in a query to find documents where a specific field exists. For example, { fieldName: { $exists: true } } returns documents that have the fieldName field.Syntax
The $exists operator checks if a field is present in a document. Use it inside a query filter like this:
{ fieldName: { $exists: true } }finds documents wherefieldNameexists.{ fieldName: { $exists: false } }finds documents wherefieldNamedoes not exist.
json
{ fieldName: { $exists: true } }Example
This example finds all documents in the users collection where the email field exists.
mongodb
db.users.find({ email: { $exists: true } })Output
[
{ "_id": 1, "name": "Alice", "email": "alice@example.com" },
{ "_id": 3, "name": "Charlie", "email": "charlie@example.com" }
]
Common Pitfalls
Common mistakes when using $exists include:
- Using
$existswithout a boolean value (true or false) causes errors. - Confusing
$exists: truewith checking for non-null or non-empty values;$existsonly checks presence, not value content. - For nested fields, ensure the full path is used, e.g.,
{ 'address.city': { $exists: true } }.
mongodb
/* Wrong: Missing boolean value */ db.users.find({ email: { $exists: "yes" } }) /* Right: Use boolean true */ db.users.find({ email: { $exists: true } })
Quick Reference
| Query | Description |
|---|---|
| { fieldName: { $exists: true } } | Find documents where fieldName exists |
| { fieldName: { $exists: false } } | Find documents where fieldName does not exist |
| { 'nested.field': { $exists: true } } | Find documents where nested.field exists |
Key Takeaways
Use the $exists operator with true to find documents where a field exists.
Always provide a boolean value (true or false) with $exists.
$exists only checks if the field is present, not its value.
Use dot notation to check nested fields.
Common errors come from missing or wrong $exists values.