Query Nested Data
In this step, you'll learn how to query nested documents and arrays in MongoDB. We'll explore different techniques to filter and retrieve specific nested data.
First, let's reset our database with some sample data to demonstrate querying:
mongosh
Switch to the bookstore database:
use bookstore
Let's insert multiple books with nested structures:
db.books.insertMany([
{
title: "MongoDB Essentials",
author: {
name: "John Doe",
experience: { years: 5, specialization: "Database Design" }
},
tags: ["beginner", "database", "nosql"],
chapters: [
{ number: 1, title: "Introduction", pages: 25 },
{ number: 2, title: "Advanced Concepts", pages: 45 }
]
},
{
title: "Advanced Database Techniques",
author: {
name: "Jane Smith",
experience: { years: 8, specialization: "Distributed Systems" }
},
tags: ["advanced", "distributed", "nosql"],
chapters: [
{ number: 1, title: "System Design", pages: 35 },
{ number: 2, title: "Performance Optimization", pages: 55 }
]
}
])
Query a book by a nested field:
db.books.find({ "author.name": "John Doe" })
Query using dot notation for nested objects:
db.books.find({ "author.experience.specialization": "Database Design" })
Query using array contains:
db.books.find({ tags: "nosql" })
Query nested array elements:
db.books.find({ "chapters.pages": { $gt: 40 } })
The $gt
operator means "greater than", so this finds books with chapters longer than 40 pages.
Complex query combining nested object and array conditions:
db.books.find({
"author.experience.years": { $gte: 5 },
tags: "advanced"
})
This finds books by authors with 5 or more years of experience and tagged as "advanced".