$unwind (Deconstruct Array)
Last updated: 2026-10-09
$unwind (Deconstruct Array)
$unwind deconstructs an array field, emitting one document per element while copying all other fields. Use it to flatten arrays before grouping, statistics, or lookups. Documents with empty, missing, or null arrays are dropped by default; preserveNullAndEmptyArrays keeps them and includeArrayIndex exposes the element index. Unwinding multiplies the document count, so budget later stages accordingly.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $unwind: { path: "$arrayField", preserveNullAndEmptyArrays: <bool>, includeArrayIndex: "<indexField>" } }
⚙️ Parameters
| path | Path of the array field to deconstruct, prefixed with $. |
|---|---|
| preserveNullAndEmptyArrays | When true, keeps documents with empty, missing, or null arrays. |
| includeArrayIndex | Outputs each element's index in the original array to this field. |
Returns:Flattened document stream (one document per array element)
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $unwind: deconstruct the tags array
db.inventory.aggregate([
{ $unwind: { path: '$tags', includeArrayIndex: 'idx' } }
])
Output:
{ "_id": 1, "item": "Pen", "tags": "A", "idx": 0 }
{ "_id": 1, "item": "Pen", "tags": "B", "idx": 1 }
📌 Notes
- Documents with empty, missing, or null arrays are dropped unless preserveNullAndEmptyArrays is set
- includeArrayIndex exposes the element's original index
- Pair $unwind with $group or $lookup for per-element statistics or joins
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Hands-On: CRUD for a Blog Comment System
$lookup and Associations with Multiple Sets
📚 Related Tutorials
❓ FAQ
QDo documents produced by $unwind share the same _id?
AYes. _id and all other fields are copied verbatim; only the array field becomes a single element.
QWhat happens when $unwind hits an empty array?
AThe document is dropped by default; set preserveNullAndEmptyArrays to true to keep it.
QCan multiple array fields be unwound at once?
AOne $unwind handles one array. Chain multiple $unwind stages for several arrays, which yields a Cartesian product.