Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the $unwind operator in MongoDB?
The $unwind operator in MongoDB deconstructs an array field from input documents to output a document for each element. Each output document contains the same fields as the original document, but the array field is replaced with a single array element.
Syntax
db.collection.aggregate([
{ $unwind: "$arrayField" }
]);
Sample Data
Let us create a collection with a document containing an array ?
db.unwindOperatorDemo.insertOne({
"StudentName": "Larry",
"StudentAge": 23,
"StudentSubject": ["C", "C++", "Java", "MongoDB"]
});
{
"acknowledged": true,
"insertedId": ObjectId("5c7ef5f3559dd2396bcfbfc8")
}
Display the document to see the original structure ?
db.unwindOperatorDemo.find().pretty();
{
"_id": ObjectId("5c7ef5f3559dd2396bcfbfc8"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentSubject": [
"C",
"C++",
"Java",
"MongoDB"
]
}
Example: Using $unwind Operator
Apply the $unwind operator to deconstruct the StudentSubject array ?
db.unwindOperatorDemo.aggregate([
{ $project: {
StudentName: 1,
StudentAge: 1,
StudentSubject: 1
}},
{ $unwind: "$StudentSubject" }
]).pretty();
{
"_id": ObjectId("5c7ef5f3559dd2396bcfbfc8"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentSubject": "C"
}
{
"_id": ObjectId("5c7ef5f3559dd2396bcfbfc8"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentSubject": "C++"
}
{
"_id": ObjectId("5c7ef5f3559dd2396bcfbfc8"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentSubject": "Java"
}
{
"_id": ObjectId("5c7ef5f3559dd2396bcfbfc8"),
"StudentName": "Larry",
"StudentAge": 23,
"StudentSubject": "MongoDB"
}
How It Works
The $unwind operator transforms one document with an array into multiple documents. Each output document contains the original fields (StudentName and StudentAge) paired with a single element from the array field (StudentSubject).
Conclusion
The $unwind operator is essential for processing array fields in aggregation pipelines. It creates separate documents for each array element, enabling further operations on individual array values.
