tezvyn:

MongoDB aggregation pipeline for total sales

AI-drafted, machine-checkedSource: interviewadvanced
WHAT IT TESTS

knowledge of aggregation stages.

OUTLINE

explain the pipeline as ordered stages, use $group with $sum to total per productId, $match on the computed total, then $sort descending.

RED FLAG

trying to filter the sum with $match before $group.

WHAT THIS TESTS Whether you can express a real analytical query in MongoDB and understand that aggregation is an ordered, multi-stage pipeline rather than a single filter.

A GOOD ANSWER COVERS The aggregation framework feeds documents through a sequence of stages where the output of one stage becomes the input of the next. Common stages are match (filter), group (collapse documents and compute accumulators like sum), sort, project, and lookup for joins. For this problem you group by productId and accumulate the total, then filter on that computed total, then sort. Order is essential: a match on totalSales must come after group because the field does not exist until grouping creates it. An early match on raw fields (like date or status) can precede group to reduce work, leveraging indexes.

COMMON WRONG ANSWERS Placing match on the aggregated total before group, forgetting that $group _id holds the grouping key, or pulling all documents into Node and summing in JavaScript, which does not scale.

LIKELY FOLLOW-UPS Why early match improves performance, the difference between group and project, using lookup to join the products collection, and how indexes affect the pipeline.

ONE CONCRETE EXAMPLE Sale.aggregate with stages: first group with _id set to productId and totalSales set to sum of amount; then match where totalSales is greater than 1000; then sort with totalSales set to negative one for descending. This returns one document per qualifying product, each holding its productId and summed totalSales, ordered from highest to lowest.

Read the original → mongoosejs.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.