$unwind: Deconstructing Array Fields
Learners will flatten an array field into individual documents with $unwind and combine it with $group for per-element analytics.
What Does $unwind Do?
The $unwind stage deconstructs an array field in a document into multiple output documents—one per array element. Each output document is a copy of the original document with the array field replaced by a single element from the array. This is essential for per-element analytics, like counting how many times each tag appears across all articles in a collection.
// Input document:
// { title: 'MongoDB Guide', tags: ['nosql', 'database', 'mongodb'] }
db.articles.aggregate([
{ $unwind: '$tags' }
]);
// Output: THREE documents:
// { title: 'MongoDB Guide', tags: 'nosql' }
// { title: 'MongoDB Guide', tags: 'database' }
// { title: 'MongoDB Guide', tags: 'mongodb' }Basic $unwind Syntax
The simplest form of $unwind is a string with the dollar-prefixed field path: { $unwind: '$arrayField' }. The extended object syntax allows additional options like preserving empty arrays and including the array index. For most cases, the simple string form is sufficient.
// Simple string form
db.products.aggregate([
{ $unwind: '$reviews' }
]);
// Extended object form with options
db.products.aggregate([
{ $unwind: {
path: '$reviews',
includeArrayIndex: 'reviewIndex', // add index field
preserveNullAndEmptyArrays: true // keep docs with no reviews
}}
]);All lessons in this course
- $lookup: Joining Collections in the Pipeline
- $unwind: Deconstructing Array Fields
- $addFields, $replaceRoot, and $mergeObjects
- $out and $merge: Writing Pipeline Results