0
0
MongodbHow-ToBeginner · 3 min read

How to Use $unwind in Aggregation in MongoDB

Use the $unwind stage in a MongoDB aggregation pipeline to deconstruct an array field from input documents and output a document for each element. This helps to flatten arrays so you can process each element individually in subsequent pipeline stages.
📐

Syntax

The $unwind stage takes an object or a string specifying the array field to deconstruct. It outputs one document per element in the array.

  • { $unwind: "$arrayField" }: Basic syntax to unwind the array field.
  • { $unwind: { path: "$arrayField", includeArrayIndex: "indexField", preserveNullAndEmptyArrays: true|false } }: Advanced syntax with options.

Options explained:

  • path: The array field to unwind (required).
  • includeArrayIndex: Optional field name to add the array index of the element.
  • preserveNullAndEmptyArrays: If true, keeps documents where the array is null, missing, or empty.
json
{
  $unwind: {
    path: "$arrayField",
    includeArrayIndex: "arrayIndex",
    preserveNullAndEmptyArrays: false
  }
}
💻

Example

This example shows how to unwind the hobbies array field from documents, creating one output document per hobby.

mongodb
db.users.aggregate([
  { $unwind: "$hobbies" },
  { $project: { name: 1, hobby: "$hobbies" } }
])
Output
[ { "_id": ObjectId("..."), "name": "Alice", "hobby": "reading" }, { "_id": ObjectId("..."), "name": "Alice", "hobby": "hiking" }, { "_id": ObjectId("..."), "name": "Bob", "hobby": "cooking" } ]
⚠️

Common Pitfalls

Common mistakes when using $unwind include:

  • Unwinding a field that is not an array causes errors.
  • Not using preserveNullAndEmptyArrays when arrays can be empty or missing, which causes documents to be dropped.
  • Forgetting that $unwind increases the number of documents, which can impact performance.
mongodb
/* Wrong: unwinding a non-array field */
db.collection.aggregate([
  { $unwind: "$nonArrayField" }
])

/* Right: check or ensure the field is an array before unwinding or use preserveNullAndEmptyArrays */
db.collection.aggregate([
  { $unwind: { path: "$maybeArrayField", preserveNullAndEmptyArrays: true } }
])
📊

Quick Reference

OptionDescription
pathThe array field to unwind (required)
includeArrayIndexOptional field name to add the element's index
preserveNullAndEmptyArraysKeep documents with null, missing, or empty arrays if true

Key Takeaways

Use $unwind to flatten array fields into multiple documents in aggregation.
Include the includeArrayIndex option to track element positions if needed.
Set preserveNullAndEmptyArrays to true to keep documents without array elements.
Unwinding non-array fields causes errors; ensure the field is an array.
$unwind increases document count, so use it thoughtfully for performance.