MongoDB Query to Flatten Array Using $unwind
$unwind to flatten an array field into multiple documents, like { $unwind: "$arrayField" }.Examples
How to Think About It
$unwind operator does this by taking each element of the array and creating a separate output document for it, effectively 'flattening' the array.Algorithm
Code
db.collection.aggregate([
{ $unwind: "$items" }
])Dry Run
Let's trace flattening the array ["apple", "banana"] in the document { _id: 1, items: ["apple", "banana"] }.
Input Document
{ _id: 1, items: ["apple", "banana"] }
Apply $unwind
Split array into two documents: { _id: 1, items: "apple" } and { _id: 1, items: "banana" }
| _id | items |
|---|---|
| 1 | apple |
| 1 | banana |
Why This Works
Step 1: What $unwind Does
$unwind takes an array field and outputs one document per array element.
Step 2: Preserving Other Fields
All other fields in the document stay the same for each output document.
Step 3: Resulting Documents
The result is a set of documents each with a single array element, effectively flattening the array.
Alternative Approaches
db.collection.aggregate([
{ $project: {
flattened: { $reduce: {
input: "$arrayField",
initialValue: [],
in: { $concatArrays: ["$$value", ["$$this"]] }
}}
}}
])db.collection.aggregate([
{ $unwind: { path: "$arrayField", preserveNullAndEmptyArrays: true } }
])Complexity: O(n) time, O(n) space
Time Complexity
The operation processes each element in the array once, so time grows linearly with the total number of array elements.
Space Complexity
Output documents increase with the number of array elements, so space usage is proportional to the flattened size.
Which Approach is Fastest?
$unwind is the most efficient for flattening arrays into separate documents; alternatives may be slower or more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $unwind | O(n) | O(n) | Splitting array elements into separate documents |
| $project with $reduce | O(n) | O(n) | Flattening nested arrays into a single array |
| $unwind with preserveNullAndEmptyArrays | O(n) | O(n) | Flattening while keeping empty or missing arrays |
$unwind to flatten arrays quickly in aggregation pipelines.$unwind and trying to flatten arrays with simple find queries.