Skip to main content

馃憪 Group

We can sum all the pages for all books in each year:

[
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}}
]

Here, we group by the book's year (the _id of the grouping), and then we create a new field called totalPages that's the sum of all pages.

馃憪 Can you get the results ordered ascending by year?

Answer
[
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}},
{$sort: {_id: 1}}
]

馃憪 Can you get the average pages per year (hint: use $avg)?

Answer
[
{$group:{
_id: "$year",
totalPages: {$avg: "$pages"}
}},
{$sort: {_id: 1}}
]

馃憪 Which year had the most printed-out pages?

Answer
[
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}},
{$sort: {totalPages: -1}},
{$limit: 1}
]