MongoDB Query to Find Nested Field Value
{ 'parent.child': value } to find documents where a nested field matches the value.Examples
How to Think About It
parent.child in the query to tell MongoDB to look inside the nested object for the value.Algorithm
Code
db.users.find({ 'address.city': 'New York' })Dry Run
Let's trace the query { 'address.city': 'New York' } through the code
Identify nested field
Nested field is 'address.city' and value to find is 'New York'.
Query documents
MongoDB checks each document's 'address' object for 'city' equal to 'New York'.
Return matching documents
Documents with 'address.city' = 'New York' are returned.
| Document | address.city | Match |
|---|---|---|
| { name: 'Alice', address: { city: 'New York', zip: '10001' } } | New York | Yes |
| { name: 'Bob', address: { city: 'Boston', zip: '02101' } } | Boston | No |
Why This Works
Step 1: Dot notation access
Using parent.child tells MongoDB to look inside the nested object named parent for the field child.
Step 2: Matching value
MongoDB compares the nested field's value to the one given in the query and selects documents where they are equal.
Alternative Approaches
db.users.find({ 'orders': { $elemMatch: { 'item': 'book', 'qty': { $gt: 2 } } } })db.users.aggregate([{ $match: { $expr: { $eq: [ '$address.city', 'New York' ] } } }])Complexity: O(n) time, O(k) space
Time Complexity
The query scans documents to check the nested field, so time grows linearly with the number of documents.
Space Complexity
Only the matching documents are returned, so space depends on the result size, not the entire collection.
Which Approach is Fastest?
Simple dot notation queries are fastest for nested fields; aggregation is slower but more flexible.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Dot notation query | O(n) | O(k) | Simple nested field matches |
| $elemMatch for arrays | O(n) | O(k) | Matching multiple conditions in nested arrays |
| Aggregation $match with $expr | O(n) | O(k) | Complex nested field conditions |
'parent.child' to query nested fields easily.