0
0
MongodbHow-ToBeginner · 3 min read

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 where fieldName exists.
  • { fieldName: { $exists: false } } finds documents where fieldName does 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 $exists without a boolean value (true or false) causes errors.
  • Confusing $exists: true with checking for non-null or non-empty values; $exists only 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

QueryDescription
{ 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.