← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 7 of 7

$unwind

$unwind splits an array field so each element becomes its own document.

In this page:

  1. $unwind
Syntax
javascript
{ $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

bash
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
  1. Expecting empty arrays to be kept
  2. Forgetting the $ in the path
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.