MongoDB Aggregation Stages Operator - $unwind
Description
The MongoDB $unwind stages operator is used to deconstructing an array field from the input documents to output a document for each element. Every output document is the input document with the value of the array field replaced by the element.
Syntax:
{ $unwind: <field path> }
Points to remember:
- If the value of a field is not an array, db.collection.aggregate() generates an error.
- If the specified path for a field does not exist in an input document, the pipeline ignores the input document and displaying no output.
- If the array is empty in an input document, the pipeline ignores the input document and displaying no output.
Sample collection test1
{
"_id" : 1,
"shirt" : "Half Sleeve",
"sizes" : [
"medium",
"XL",
"free"
]
}
{ "_id" : 2, "shirt" : "Full Sleeve", "sizes" : [ ] }
Example: $unwind
The following aggregation $unwind stage is used to output a document for each element in the sizes array.
> db.test1.aggregate( [ { $unwind : "$sizes" } ] );
Output:
> db.test1.aggregate( [ { $unwind : "$sizes" } ] ); { "_id" : 1, "shirt" : "Half Sleeve", "sizes" : "medium" } { "_id" : 1, "shirt" : "Half Sleeve", "sizes" : "XL" } { "_id" : 1, "shirt" : "Half Sleeve", "sizes" : "free" }
Here from the result it shows that, each document is identical to the input document except for the value of the sizes field that contain the value from the original sizes array.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/mongodb/aggregation/mongodb-aggregatrion-unwind-operator.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics