1 | initial version |
To deconstruct an array in MongoDB, we can use the $unwind
operator.
Let's suppose we have a collection named "students" with the following documents:
{
"_id": 1,
"name": "John",
"grades": [81, 73, 92]
}
{
"_id": 2,
"name": "Mary",
"grades": [87, 78, 95]
}
If we want to deconstruct the grades
array of each document, we can use the following query:
db.students.aggregate([
{ $unwind: "$grades" }
])
The result will be:
{ "_id": 1, "name": "John", "grades": 81 }
{ "_id": 1, "name": "John", "grades": 73 }
{ "_id": 1, "name": "John", "grades": 92 }
{ "_id": 2, "name": "Mary", "grades": 87 }
{ "_id": 2, "name": "Mary", "grades": 78 }
{ "_id": 2, "name": "Mary", "grades": 95 }
The $unwind
operator creates a new document for each element in the array, with the same values for all fields except for the field being unwound (grades
in this case). This allows us to perform aggregation operations on the individual elements of the array.