Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Aggregation Pipeline Basics
interview

Q1. What is the aggregation pipeline in MongoDB?
The aggregation pipeline is a framework for data aggregation modeled on data processing pipelines. Documents enter a multi-stage pipeline that transforms them into aggregated results. Stages like $match, $group, $sort, $project process documents sequentially. It's similar to SQL GROUP BY but more flexible.

Q2. How do you use $match and $group together?
$match filters documents, $group groups them:
db.orders.aggregate([ { $match: { status: "completed" } }, { $group: { _id: "$customerId", total: { $sum: "$amount" } } } ])
This returns total amount per customer for completed orders.

Q3. What is the $project stage?
$project reshapes documents by including, excluding, or adding fields:
db.users.aggregate([ { $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: 1 } } ])
It can also create computed fields and rename fields.

Q4. How do you sort and limit in aggregation?
Use $sort and $limit stages:
db.products.aggregate([ { $sort: { price: -1 } }, { $limit: 5 } ])
This returns the top 5 most expensive products.

Q5. What is $unwind used for?
$unwind deconstructs an array field, creating a separate document for each element:
db.orders.aggregate([ { $unwind: "$items" }, { $group: { _id: "$items.productId", totalSold: { $sum: "$items.quantity" } } } ])
This is essential for aggregating data within arrays.