Navigation
This version of the documentation is archived and no longer supported.

$unwind (aggregation)

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:

{ $unwind: <field path> }

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:

{ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] }

The following aggregation uses the $unwind stage to output a document for each element in the sizes array:

db.inventory.aggregate( [ { $unwind : "$sizes" } ] )

The operation returns the following results:

{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }

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.