The ‘$unwind‘ operator in MongoDB is used to deconstruct an array field from the input documents to output a document for each element. This is particularly useful when we have documents with an array field that we need to "flatten" for further processing.
The general syntax for the ‘$unwind‘ operator in MongoDB is as follows:
{
$unwind: {
path: "$<array_field>",
includeArrayIndex: "<index_field>",
preserveNullAndEmptyArrays: <boolean_value>
}
}
where:
- ‘"array_field"` is the name of the array field that we want to deconstruct.
- ‘"index_field"` (optional) is the name of a new field to include the index of the array element. If not specified, the ‘path‘ is a string, otherwise it is an object.
- ‘<boolean_value>‘ (optional) - when true, preserves the output array even when the input is null or empty, otherwise produces no output when the input is null or empty.
For example, consider the following MongoDB collection ‘orders‘ where each document includes an array of ‘items‘ ordered:
db.orders.insertMany([
{
"_id": 1,
"customer": "John",
"items": [
{ "sku": "111", "qty": 2, "price": 10 },
{ "sku": "222", "qty": 1, "price": 20 }
]
},
{
"_id": 2,
"customer": "Jane",
"items": [
{ "sku": "333", "qty": 5, "price": 5 },
{ "sku": "444", "qty": 10, "price": 1 }
]
}
])
If we want to calculate the total value of each order, we can use the ‘$unwind‘ operator to "flatten" the ‘items‘ array and then perform a ‘$group‘ stage to calculate the total value for each order:
db.orders.aggregate([
{
$unwind: "$items"
},
{
$group: {
_id: "$_id",
customer: { $first: "$customer" },
total: { $sum: { $multiply: ["$items.qty", "$items.price"] } }
}
}
])
The output of this aggregation pipeline will be:
[
{ "_id": 1, "customer": "John", "total": 40 },
{ "_id": 2, "customer": "Jane", "total": 55 }
]
Note that we used the ‘$first‘ operator to keep the non-array fields (‘_id‘ and ‘customer‘) from the input documents in the output. We also used the ‘$multiply‘ operator to calculate the total value for each item by multiplying the quantity with the price.
Overall, the ‘$unwind‘ operator is a powerful and useful tool in the MongoDB aggregation framework when dealing with array fields.