- Reference >
- Operators >
- Aggregation Framework Operators >
- Pipeline Aggregation Operators >
- $unwind (aggregation)
$unwind (aggregation)¶
-
$unwind¶ Peels off the elements of an array individually, and returns a stream of documents.
$unwindreturns one document for every member of the unwound array within every source document. Take the following aggregation command:Note
The dollar sign (i.e.
$) must precede the field specification handed to the$unwindoperator.In the above aggregation
$projectselects (inclusively) theauthor,title, andtagsfields, as well as the_idfield implicitly. Then the pipeline passes the results of the projection to the$unwindoperator, which will unwind thetagsfield. This operation may return a sequence of documents that resemble the following for a collection that contains one document holding atagsfield with an array of 3 items.A single document becomes 3 documents: each document is identical except for the value of the
tagsfield. Each value oftagsis one of the values in the original “tags” array.Note
$unwindhas the following behaviors:$unwindis most useful in combination with$group.- You may undo the effects of unwind operation with the
$grouppipeline operator. - If you specify a target field for
$unwindthat does not exist in an input document, the pipeline ignores the input document, and will generate no result documents. - If you specify a target field for
$unwindthat is not an array,db.collection.aggregate()generates an error. - If you specify a target field for
$unwindthat holds an empty array ([]) in an input document, the pipeline ignores the input document, and will not generate any result documents.