$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 totrue
, documents that have missing ornull
values for the array field, or where the array is empty, will be preserved, with the array field set tonull
.
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
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.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.Field Types:
$unwind
only works on array fields. If the specified field is not an array, the pipeline will return an error unlesspreserveNullAndEmptyArrays
is set totrue
.