0
0
MongodbHow-ToBeginner · 2 min read

MongoDB Query to Unwind Array with $unwind Operator

Use the MongoDB aggregation pipeline stage { $unwind: "$arrayField" } to flatten an array field into multiple documents, one per array element.
📋

Examples

Input{ _id: 1, fruits: ["apple", "banana"] }
Output{ _id: 1, fruits: "apple" } { _id: 1, fruits: "banana" }
Input{ _id: 2, colors: ["red"] }
Output{ _id: 2, colors: "red" }
Input{ _id: 3, items: [] }
Output
🧠

How to Think About It

To unwind an array in MongoDB, think of splitting each document into multiple documents, one for each element in the array. The $unwind operator does this by taking the array field and creating a separate document for each item inside it.
📐

Algorithm

1
Start with the collection containing documents with array fields.
2
Apply the <code>$unwind</code> stage on the array field you want to flatten.
3
MongoDB outputs one document per element in the array, duplicating other fields.
4
Collect the resulting documents as the output of the aggregation.
💻

Code

mongodb
db.collection.aggregate([
  { $unwind: "$fruits" }
])
Output
{ "_id" : 1, "fruits" : "apple" } { "_id" : 1, "fruits" : "banana" }
🔍

Dry Run

Let's trace unwinding the array ["apple", "banana"] in the fruits field.

1

Original Document

{ _id: 1, fruits: ["apple", "banana"] }

2

Apply $unwind

Split into two documents: { _id: 1, fruits: "apple" } { _id: 1, fruits: "banana" }

_idfruits
1apple
1banana
💡

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

Use $unwind with preserveNullAndEmptyArrays
mongodb
db.collection.aggregate([
  { $unwind: { path: "$fruits", preserveNullAndEmptyArrays: true } }
])
Keeps documents with empty or missing arrays instead of removing them.
Use $project with $arrayElemAt for specific elements
mongodb
db.collection.aggregate([
  { $project: { firstFruit: { $arrayElemAt: ["$fruits", 0] } } }
])
Extracts only one element instead of unwinding all; useful for limited cases.

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.

ApproachTimeSpaceBest For
$unwindO(n*m)O(n*m)Flattening arrays fully
$unwind with preserveNullAndEmptyArraysO(n*m)O(n*m)Flattening while keeping empty arrays
$project with $arrayElemAtO(n)O(n)Extracting specific array elements
💡
Use $unwind to flatten arrays before filtering or grouping by array elements.
⚠️
Forgetting that $unwind duplicates documents for each array element, which can increase result size.