- Reference >
- Operators >
- Aggregation Pipeline Operators >
- Pipeline Aggregation Stages >
- $unwind (aggregation)
$unwind (aggregation)¶
On this page
Definition¶
-
$unwind
¶ Deconstructs an array field from the input documents to output a document for each element. Each output document is the input document with the value of the array field replaced by the element.
The
$unwind
stage has the following prototype form:To specify a field path, prefix the field name with a dollar sign
$
and enclose in quotes.
Behaviors¶
$unwind
has the following behaviors:
- If a value in the field specified by the field path is not an
array,
db.collection.aggregate()
generates an error. - If you specify a path for a field that does not exist in an input document, the pipeline ignores the input document and will not output documents for that input document.
- If the array holds an empty array (
[]
) in an input document, the pipeline ignores the input document and will not output documents for that input document.
Examples¶
Consider an inventory
with the following document:
The following aggregation uses the $unwind
stage to output
a document for each element in the sizes
array:
The operation returns the following results:
Each document is identical to the input document except for the value
of the sizes
field which now holds a value from the original
sizes
array.