- Reference >
- Query, Update, Projection, and Aggregation Operators >
- $unwind (aggregation)
$unwind (aggregation)¶
-
$unwind
¶ Peels off the elements of an array individually, and returns a stream of documents.
$unwind
returns 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 proceed the field specification handed to the$unwind
operator.In the above aggregation
$project
selects (inclusively) theauthor
,title
, andtags
fields, as well as the_id
field implicitly. Then the pipeline passes the results of the projection to the$unwind
operator, which will unwind thetags
field. This operation may return a sequence of documents that resemble the following for a collection that contains one document holding atags
field with an array of 3 items.A single document becomes 3 documents: each document is identical except for the value of the
tags
field. Each value oftags
is one of the values in the original “tags” array.Note
$unwind
has the following behaviors:$unwind
is most useful in combination with$group
.- You may undo the effects of unwind operation with the
$group
pipeline operator. - If you specify a target field for
$unwind
that 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
$unwind
that is not an array,db.collection.aggregate()
generates an error. - If you specify a target field for
$unwind
that holds an empty array ([]
) in an input document, the pipeline ignores the input document, and will generates no result documents.