0
0
MongodbHow-ToBeginner · 3 min read

How to Query Nested Documents in MongoDB Easily

To query nested documents in MongoDB, use dot notation to specify the path to the nested field inside the document. For example, { "address.city": "New York" } finds documents where the nested city field inside address equals "New York".
📐

Syntax

Use { "field.nestedField": value } to query nested fields inside documents. The dot . separates the parent field from the nested field.

You can also use operators like $elemMatch for arrays of nested documents.

json
{ "parentField.nestedField": "value" }
💻

Example

This example shows how to find users living in the city "New York" where the city is nested inside the address document.

mongodb
db.users.find({ "address.city": "New York" })
Output
[ { "_id": ObjectId("..."), "name": "Alice", "address": { "city": "New York", "zip": "10001" } } ]
⚠️

Common Pitfalls

  • For nested arrays, querying with dot notation matches any element, which may cause unexpected results.
  • Using dot notation on fields that are not objects or arrays will not work.
  • To query nested arrays of documents, use $elemMatch to specify multiple conditions on the same element.
mongodb
/* Wrong: This matches documents where any address has city "New York" and zip "10001" but not necessarily in the same element */
db.users.find({ "address.city": "New York", "address.zip": "10001" })

/* Right: Use $elemMatch to match both conditions in the same nested document */
db.users.find({ "address": { $elemMatch: { city: "New York", zip: "10001" } } })
📊

Quick Reference

Query TypeSyntax ExampleDescription
Simple nested field{ "field.nested": value }Matches documents where nested field equals value
Array of nested docs{ "arrayField.nested": value }Matches if any element's nested field equals value
Multiple conditions in array{ "arrayField": { $elemMatch: { cond1, cond2 } } }Matches elements meeting all conditions
Existence check{ "field.nested": { $exists: true } }Checks if nested field exists

Key Takeaways

Use dot notation to access nested fields in MongoDB queries.
For arrays of nested documents, use $elemMatch to match multiple conditions on the same element.
Dot notation matches any element in arrays, so be careful with multiple conditions.
Always verify the structure of your documents before querying nested fields.
Use $exists to check if a nested field is present.