$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.

CategoryCore Stages
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $unwind: { path: "$arrayField", preserveNullAndEmptyArrays: <bool>, includeArrayIndex: "<indexField>" } }

⚙️ Parameters

pathPath of the array field to deconstruct, prefixed with $.
preserveNullAndEmptyArraysWhen true, keeps documents with empty, missing, or null arrays.
includeArrayIndexOutputs 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏