MongoDB Query to Find Documents Where Field Exists
{ fieldName: { $exists: true } } to find documents where the field fieldName exists.Examples
How to Think About It
$exists operator to test if a field is present or not. You just specify the field name and set $exists to true to get all documents that have that field.Algorithm
Code
db.collection.find({ age: { $exists: true } })Dry Run
Let's trace the query { age: { $exists: true } } through the collection.
Check first document
Document: { name: 'Alice', age: 25 } - Field 'age' exists, include this document.
Check second document
Document: { name: 'Bob', age: 30 } - Field 'age' exists, include this document.
Check third document
Document: { name: 'Charlie' } - Field 'age' does not exist, exclude this document.
| Document | Field 'age' Exists? | Include in Result? |
|---|---|---|
| { name: 'Alice', age: 25 } | Yes | Yes |
| { name: 'Bob', age: 30 } | Yes | Yes |
| { name: 'Charlie' } | No | No |
Why This Works
Step 1: Using $exists operator
The $exists operator checks if a field is present in a document, regardless of its value.
Step 2: Setting $exists to true
Setting $exists: true means the query matches documents where the field is present.
Step 3: Query returns matching documents
MongoDB returns all documents that have the specified field, ignoring documents where the field is missing.
Alternative Approaches
db.collection.find({}, { age: 1 })db.collection.find({ age: { $exists: false } })Complexity: O(n) time, O(k) space
Time Complexity
The query scans each document in the collection to check if the field exists, so it is O(n) where n is the number of documents.
Space Complexity
The space used depends on the number of matching documents returned, O(k), where k is the count of documents with the field.
Which Approach is Fastest?
Using $exists is the most direct and efficient way to check field presence compared to filtering or projections.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $exists: true | O(n) | O(k) | Filtering documents by field presence |
| Projection only | O(n) | O(n) | Viewing specific fields without filtering |
| $exists: false | O(n) | O(k) | Finding documents missing a field |
$exists: true to quickly filter documents that have a specific field.$exists and trying to check field presence with equality operators.