$unwind
$unwind splits an array field so each element becomes its own document.
In this page:
Syntax
{ $unwind: "$array_field" }
$unwind
For a document with array [a, b, c], $unwind outputs three documents, each with one element in that field. Documents with empty or missing arrays are dropped unless preserveNullAndEmptyArrays is true.
It is often paired with $group to count or total elements.
Note:
Use preserveNullAndEmptyArrays to keep documents with empty arrays.
Example: $unwind
test> db.posts.insertMany([{ _id: 1, title: "A", tags: ["js", "db"] }, { _id: 2, title: "B", tags: ["js"] }, { _id: 3, title: "C", tags: [] }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2, '2': 3 } }
test> db.posts.aggregate([{ $unwind: "$tags" }, { $project: { _id: 0, title: 1, tags: 1 } }])
[
{ title: 'A', tags: 'js' },
{ title: 'A', tags: 'db' },
{ title: 'B', tags: 'js' }
]
test> db.posts.aggregate([{ $unwind: "$tags" }, { $group: { _id: "$tags", posts: { $sum: 1 } } }, { $sort: { _id: 1 } }])
[ { _id: 'db', posts: 1 }, { _id: 'js', posts: 2 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Expecting empty arrays to be kept
- Forgetting the $ in the path
- Forgetting unwinding multiplies documents
Chapter Summary
- $unwind emits one document per element
- Empty arrays drop the document
- preserveNullAndEmptyArrays keeps them
- Pairs well with $group
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: