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 read on 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 $group with a great many groups needs more memory; with allowDiskUse it spills to disk instead of failing.

See also