馃憪 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}
])