LESSON 20 / 20·2 min readAdvanced

What is a simple aggregation example?

01 Understand02 Recall03 Prepare

Understand the concept

This pipeline is a reporting query that first selects paid orders and then totals each customer's amount. Grouping reduces many order documents into one result per customer, after which sorting and limiting choose the top five. It demonstrates why filtering before expensive aggregation can be valuable.

Example and explanation:

JavaScript
db.orders.aggregate([
  { $match: { status: 'paid' } },
  { $group: { _id: '$customerId', total: { $sum: '$amount' } } },
  { $sort: { total: -1 } },
  { $limit: 5 }
]);
  • Returns the five customers with the largest paid order totals.

  • An early filter reduces the input to the grouping stage.

  • Use a suitable exact monetary representation, such as integer minor units or Decimal128, when amounts require exact arithmetic.

PAUSE & RECALL

Can you explain it without the notes?

What is a simple aggregation example?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

This pipeline is a reporting query that first selects paid orders and then totals each customer's amount. Grouping reduces many order documents into one result per customer, after which sorting and limiting choose the top five. It demonstrates why filtering before expensive aggregation can be valuable.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Clarify currency and ties at the fifth position if those affect the business definition of “top customers.”
Practice this concept
YOUR NEXT STEP

You’ve reached the end of this guide.

Prepare for MongoDB & Mongoose interviews

Adapted from 04_MONGODB_MONGOOSE.md · “What is a simple aggregation example?”. Examples are study fragments; framework behavior can depend on your version.