π Combining stages
Up until now, we've just been using one stage in the pipeline. But the power of the aggregation pipeline is that we can use many stages, and the output of one will be the input of the next. Think of it as UNIX pipes or using functional programming with map
, filter
, reduce
, flatmap
, etc.
Get 5 books from 2001 with more than 50 pages. Show only the title and authors.
- Atlas UI
- MongoDB Shell
[
{ $match: { year: 2001, pages: {$gt: 50 } } },
{ $project: { _id: 0, title: 1, authors: 1 } },
{ $limit: 5 },
]
db.books.aggregate([
{ $match: { year: 2001, pages: {$gt: 50 } } },
{ $project: { _id: 0, title: 1, authors: 1 } },
{ $limit: 5 },
])
We're using here the greater than $gt
operator. You have $gt
, $gte
, $lt
, etc.
π Get 15 books from 1985 with less than 150 pages. Show only the title
, year
, totalInventory
, and available
books. If you don't remember which fields we have, you can refer to the sample document.
Answer
- Atlas UI
- MongoDB Shell
[
{ $match: { year: 1985, pages: { $lt: 150 } } },
{ $project: { _id: 0, title: 1, year: 1, totalInventory: 1, available: 1 } },
{ $limit: 15 },
]
db.books.aggregate([
{ $match: { year: 1985, pages: { $lt: 150 } } },
{ $project: { _id: 0, title: 1, year: 1, totalInventory: 1, available: 1 } },
{ $limit: 15 },
])