MongoDB Tutorial
- Home
- Introduction
- Installation
- Connection & Databases
- CRUD Operations
- Comparison Operators
- Logical Operators
- Array Operators
- Evaluation Operators
- Update Operators
- Projection & Sorting
- Cursor Methods
- Querying Nested Docs
- Upserts & Indexes
- Aggregation Framework
- Data Modeling
- Validations & Transactions
- Geospatial Queries
- Advanced Indexing
- MongoDB with Next.js
- Best Practices
Querying Nested Docs
One of MongoDB's greatest strengths is its ability to handle complex, nested data. To query these fields, we use Dot Notation.
1. Querying Nested Documents
Access sub-fields by joining the field names with a dot.
// Find users lives in "NYC"
db.users.find({ "address.city": "NYC" })
// Note: Field names MUST be in quotes when using dot notation
// CORRECT: "address.city": "..."
// INCORRECT: address.city: "..."2. Querying Arrays of Documents
When an array contains documents, you can query specific fields within those documents.
// Find blogs where at least one comment is by "Alice"
db.blogs.find({ "comments.author": "Alice" })
// Exact Match (Matches the whole document in the array)
db.blogs.find({
comments: { author: "Alice", text: "Nice post!" }
})3. The $ Positional Operator
The `$` operator identifies an element in an array to update without specifying the element's position in the array.
// Update the score of the product "xyz" in the results array
db.survey.updateOne(
{ "results.product": "xyz" },
{ $set: { "results.$.score": 10 } }
)Key Rule: Dot notation allows you to reach any depth in your document structure, making MongoDB highly flexible for real-world hierarchical data.