0
0
MongoDBquery~5 mins

$unwind for flattening arrays in MongoDB

Choose your learning style9 modes available
Introduction

$unwind helps to take a list inside a document and make each item in that list its own document. This makes it easier to work with each item separately.

You have a list of hobbies inside a person's record and want to see each hobby on its own line.
You want to count how many times each item appears in a list inside documents.
You need to filter or sort based on items inside a list.
You want to join or match documents based on items inside an array.
You want to create reports that show each element of an array as a separate entry.
Syntax
MongoDB
db.collection.aggregate([
  { $unwind: "$arrayField" }
])

Replace collection with your collection name.

Replace arrayField with the name of the array you want to flatten.

Examples
This takes each hobby from the hobbies array and makes a separate document for it.
MongoDB
db.people.aggregate([
  { $unwind: "$hobbies" }
])
Flattens the items array in orders so each item is its own document.
MongoDB
db.orders.aggregate([
  { $unwind: "$items" }
])
If tags array is empty or missing, $unwind will remove that document by default.
MongoDB
db.products.aggregate([
  { $unwind: "$tags" }
])
This keeps documents even if the tags array is empty or missing.
MongoDB
db.products.aggregate([
  { $unwind: { path: "$tags", preserveNullAndEmptyArrays: true } }
])
Sample Program

This example inserts four people. Some have hobbies, some have empty or missing hobbies. The $unwind stage flattens hobbies so each hobby is a separate document. The option preserveNullAndEmptyArrays: true keeps people with no hobbies in the result.

MongoDB
db.people.insertMany([
  { _id: 1, name: "Alice", hobbies: ["reading", "swimming"] },
  { _id: 2, name: "Bob", hobbies: ["cycling"] },
  { _id: 3, name: "Carol", hobbies: [] },
  { _id: 4, name: "Dave" }
])

// Use $unwind to flatten hobbies

const result = db.people.aggregate([
  { $unwind: { path: "$hobbies", preserveNullAndEmptyArrays: true } }
]).toArray()

printjson(result)
OutputSuccess
Important Notes

Time complexity depends on the number of documents and the size of the arrays inside them.

Space complexity increases because one document with an array becomes many documents.

A common mistake is forgetting preserveNullAndEmptyArrays and losing documents with empty or missing arrays.

Use $unwind when you want to work with each array item separately. If you want to keep arrays as they are, do not use $unwind.

Summary

$unwind turns each item in an array into its own document.

It helps to analyze or filter array items easily.

Remember to use preserveNullAndEmptyArrays if you want to keep documents without array items.