Skip to content

Aggregation Fundamentals

What is Aggregation?

Transforming many documents into an answer: totals, rankings, and shapes find() cannot return.

BeginnerAbout 4 minutes

find returns documents that already exist. Aggregation returns documents you compute: totals per customer, counts per city, a ranking. If the answer is not sitting in one field on one document, you aggregate.

find()

  • Filter, project, sort, limit
  • Each result was a stored document
  • Rahul's user row, unchanged

aggregate()

  • Same filters, plus reshape and combine
  • Results can be new shapes
  • Rahul's total spend — no such field on orders
db.orders.aggregate([
  { $match: { status: { $ne: "cancelled" } } },
  { $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } }
])
find cannot give you this number without you summing in Node
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), totalSpent: 18400 }

SQL people: this is GROUP BY plus more — you can also reshape, unwind arrays, and (later) $lookup. Do not pull every order into Node to reduce. The next lesson is the pipeline those stages sit in.

Interview question

When do you use aggregation instead of find()?

Think about it first.