Problem Statement
What does the $unwind stage do in an aggregation pipeline?
Explanation
The dollar unwind stage deconstructs an array field from input documents and outputs one document for each array element. This is useful when you need to perform operations on individual array elements.
For example, if a document has an array of items, dollar unwind creates separate documents for each item, allowing you to group or aggregate based on individual items. This is commonly used before dollar group when working with arrays.
Code Solution
SolutionRead Only
// Unwind order items
db.orders.aggregate([
{ $unwind: "$items" },
{
$group: {
_id: "$items.productId",
totalQuantity: { $sum: "$items.quantity" }
}
}
])
// Before: { items: ["A", "B", "C"] }
// After: 3 docs with items: "A", items: "B", items: "C"