Skip to main content

πŸ‘ 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 10 books from 2001 with 200 pages. Show only the title and authors.

[
{
$match: { year: 2001, pages: 200 }
},
{
$project: { _id: 0, title: 1, authors: 1 }
},
{
$limit: 10
},
]

πŸ‘ Get 15 books from 1985 with 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
[
{
$match: { year: 1985, pages: 150 }
},
{
$project: { _id: 0, title: 1, year: 1, totalInventory: 1, available: 1 }
},
{
$limit: 15
},
]