Skip to main content

$unwind

The $unwind stage in MongoDB's aggregation pipeline is used to deconstruct an array field from the input documents, generating a new document for each element in the array. Each new document replaces the original document and contains all its fields except for the array, which is replaced by an element from the array. This is particularly useful when you have an array of objects or values and you want to flatten it out for easier processing in subsequent stages.

Basic Syntax

The basic syntax of the $unwind stage is as follows:

db.collection.aggregate([
{
$unwind: {
path: <array field path>,
includeArrayIndex: <index field name>,
preserveNullAndEmptyArrays: <boolean>
}
}
]);
  • path: The path of the array field to unwind, prefixed with a $.
  • includeArrayIndex: Optional. The name of a new field that will hold the array index of the unwound element.
  • preserveNullAndEmptyArrays: Optional. If set to true, documents that have missing or null values for the array field, or where the array is empty, will be preserved, with the array field set to null.

Examples

Basic Unwinding

To unwind an array field named items:

db.orders.aggregate([
{
$unwind: "$items"
}
]);

Including Array Index

To include the array index in a new field named arrayIndex:

db.orders.aggregate([
{
$unwind: {
path: "$items",
includeArrayIndex: "arrayIndex"
}
}
]);

Preserving Null and Empty Arrays

To preserve documents with null or empty arrays:

db.orders.aggregate([
{
$unwind: {
path: "$items",
preserveNullAndEmptyArrays: true
}
}
]);

Considerations

  1. Document Duplication: The $unwind stage can significantly increase the number of documents in the pipeline, especially if the array fields have many elements. This could lead to performance issues.

  2. Order of Stages: The placement of $unwind in the pipeline matters. Using $unwind early in the pipeline may lead to processing a large number of documents in subsequent stages, affecting performance.

  3. Field Types: $unwind only works on array fields. If the specified field is not an array, the pipeline will return an error unless preserveNullAndEmptyArrays is set to true.