Query Parent Children
In this step, we'll explore advanced querying techniques to retrieve related documents across parent and child collections in MongoDB. We'll demonstrate how to effectively find and join related data.
Basic Filtering Queries
Let's start by finding books by a specific author:
db.books.find({ author_id: ObjectId("author1") })
Filtering with Multiple Conditions
Query books with multiple filters:
db.books.find({
author_id: ObjectId("author1"),
published: { $gt: 1812 }
})
This query finds books by Jane Austen published after 1812.
Aggregation Pipeline for Complex Queries
Use the aggregation framework to join author and book information:
db.books.aggregate([
{ $lookup: {
from: "authors",
localField: "author_id",
foreignField: "_id",
as: "author_details"
}},
{ $match: {
"author_details.nationality": "British"
}},
{ $project: {
title: 1,
published: 1,
"author_name": "$author_details.name"
}}
])
Example Output
[
{
_id: ObjectId(...),
title: 'Pride and Prejudice',
published: 1813,
author_name: ['Jane Austen']
},
{
_id: ObjectId(...),
title: 'Emma',
published: 1815,
author_name: ['Charles Dickens']
}
]
Sorting and Limiting Results
Query and sort books by publication year:
db.books.find()
.sort({ published: 1 })
.limit(2)
This retrieves the two earliest published books.
Advanced Filtering with Regular Expressions
Find books with titles containing specific words:
db.books.find({
title: { $regex: /Sense/, $options: 'i' }
})
The $options: 'i'
makes the search case-insensitive.
Count books for each author:
db.books.aggregate([
{ $group: {
_id: "$author_id",
book_count: { $sum: 1 }
}},
{ $lookup: {
from: "authors",
localField: "_id",
foreignField: "_id",
as: "author_info"
}},
{ $project: {
author_name: "$author_info.name",
book_count: 1
}}
])
Example Output
[
{
_id: ObjectId("author1"),
author_name: ['Jane Austen'],
book_count: 2
},
{
_id: ObjectId("author2"),
author_name: ['Charles Dickens'],
book_count: 2
}
]