π Group
We can sum all the pages for all books in each year:
- Atlas UI
- MongoDB Shell
[
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}}
]
db.books.aggregate([
{$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
- Atlas UI
- MongoDB Shell
[
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}},
{$sort: {_id: 1}}
]
db.books.aggregate([
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}},
{$sort: {_id: 1}}
])
π Can you get the average pages per year (hint: use $avg)?
Answer
- Atlas UI
- MongoDB Shell
[
{$group:{
_id: "$year",
totalPages: {$avg: "$pages"}
}},
{$sort: {_id: 1}}
]
db.books.aggregate([
{$group:{
_id: "$year",
totalPages: {$avg: "$pages"}
}},
{$sort: {_id: 1}}
])
π Which year had the most printed-out pages?
Answer
- Atlas UI
- MongoDB Shell
[
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}},
{$sort: {totalPages: -1}},
{$limit: 1}
]
db.books.aggregate([
{$group:{
_id: "$year",
totalPages: {$sum: "$pages"}
}},
{$sort: {totalPages: -1}},
{$limit: 1}
])