Group and accumulate
Group documents by a key and compute totals or averages per group, or count its documents.
Group documents by a key with $group and compute over each group with MongoDB's accumulators.
Requirements
- A connection with a user that has
readon the database.
Group and sum
JavaScript
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$customer", total: { $sum: "$total" }, orders: { $count: {} }, average: { $avg: "$total" } } },
{ $sort: { total: -1 } },
]);Keep the first and the last
JavaScript
db.orders.aggregate([{ $sort: { created: 1 } }, { $group: { _id: "$customer", first: { $first: "$created" } } }]);Check
The result brings one document per customer with its totals. For the same data it always comes out in the same order.
Common problems
- A
$groupwith a great many groups needs more memory; withallowDiskUseit spills to disk instead of failing.