MongoDB Query to Unwind Array with $unwind Operator
{ $unwind: "$arrayField" } to flatten an array field into multiple documents, one per array element.Examples
How to Think About It
$unwind operator does this by taking the array field and creating a separate document for each item inside it.Algorithm
Code
db.collection.aggregate([
{ $unwind: "$fruits" }
])Dry Run
Let's trace unwinding the array ["apple", "banana"] in the fruits field.
Original Document
{ _id: 1, fruits: ["apple", "banana"] }
Apply $unwind
Split into two documents: { _id: 1, fruits: "apple" } { _id: 1, fruits: "banana" }
| _id | fruits |
|---|---|
| 1 | apple |
| 1 | banana |
Why This Works
Step 1: Why use $unwind?
The $unwind operator breaks down arrays so you can work with each element individually.
Step 2: How it works
It creates a new document for each element in the array, copying other fields as is.
Step 3: Result
You get multiple documents from one, each with a single array element.
Alternative Approaches
db.collection.aggregate([
{ $unwind: { path: "$fruits", preserveNullAndEmptyArrays: true } }
])db.collection.aggregate([
{ $project: { firstFruit: { $arrayElemAt: ["$fruits", 0] } } }
])Complexity: O(n*m) time, O(n*m) space
Time Complexity
The operation processes each document and each element in the array, so time grows with total array elements (n documents * m elements).
Space Complexity
Output size grows with the number of array elements, as each element produces a new document.
Which Approach is Fastest?
Using $unwind is efficient for flattening arrays; alternatives like $project extract specific elements but don't flatten.
| Approach | Time | Space | Best For |
|---|---|---|---|
| $unwind | O(n*m) | O(n*m) | Flattening arrays fully |
| $unwind with preserveNullAndEmptyArrays | O(n*m) | O(n*m) | Flattening while keeping empty arrays |
| $project with $arrayElemAt | O(n) | O(n) | Extracting specific array elements |
$unwind to flatten arrays before filtering or grouping by array elements.$unwind duplicates documents for each array element, which can increase result size.