$unwind operator - ( MongoDB Misc )
The $unwind
operator is used in MongoDB to transform an array into a stream of documents, where each document contains a single value from the original array. In this page, we will discuss the syntax, example, output, explanation, use, important points, and summary of the $unwind
operator in MongoDB.
Syntax
The $unwind
operator has the following syntax:
db.collection.aggregate({
$unwind: {
path: "arrayField"
}
})
Here, arrayField
is the name of the array field to unwind.
Example
Consider a collection named orders
with the following documents:
{
"_id": 1,
"name": "Order 1",
"items": [
{
"name": "Item 1",
"price": 10
},
{
"name": "Item 2",
"price": 20
}
]
},
{
"_id": 2,
"name": "Order 2",
"items": [
{
"name": "Item 3",
"price": 30
},
{
"name": "Item 4",
"price": 40
}
]
}
In this example, items
is an array that we want to unwind. The following query uses the $unwind
operator to unwind the items
array:
db.orders.aggregate({ $unwind: "$items" })
This will transform each document into two documents, one for each item in the items
array:
{
"_id": 1,
"name": "Order 1",
"items": {
"name": "Item 1",
"price": 10
}
},
{
"_id": 1,
"name": "Order 1",
"items": {
"name": "Item 2",
"price": 20
}
},
{
"_id": 2,
"name": "Order 2",
"items": {
"name": "Item 3",
"price": 30
}
},
{
"_id": 2,
"name": "Order 2",
"items": {
"name": "Item 4",
"price": 40
}
}
Output
The output of the $unwind
operator is a stream of documents, where each document contains a single value from the original array.
Explanation
The $unwind
operator is used to transform an array field into a stream of documents. When the $unwind
operator is applied to an array field, it creates a new document for each element in the array field, containing the entire document’s fields but only one field from the array.
Use
The $unwind
operator is useful when you want to perform aggregation operations on the elements of an array field. By unwinding the array, each element becomes a separate document, which can be filtered, sorted, or grouped as required for aggregation operations.
Important Points
- The
$unwind
operator is used to transform an array into a stream of documents. - The
$unwind
operator works only on array fields. - The
$unwind
operator creates a new document for each element in the array field.
Summary
In this page, we discussed the $unwind
operator in MongoDB. We covered the syntax, example, output, explanation, use, important points, and summary of the $unwind
operator. By using the $unwind
operator, you can transform an array field into a stream of documents and perform aggregation operations on each element of the array.