$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.
$unwind for flattening arrays in MongoDB
db.collection.aggregate([
{ $unwind: "$arrayField" }
])Replace collection with your collection name.
Replace arrayField with the name of the array you want to flatten.
db.people.aggregate([
{ $unwind: "$hobbies" }
])db.orders.aggregate([
{ $unwind: "$items" }
])db.products.aggregate([
{ $unwind: "$tags" }
])db.products.aggregate([
{ $unwind: { path: "$tags", preserveNullAndEmptyArrays: true } }
])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.
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)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.
$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.