1.$unwind explodes arrays into documents
$unwind takes a document with an array field and outputs one copy of that document per array element, with the array field replaced by a single element each time. A document with a 5-element array becomes 5 pipeline documents.
Key features
- $unwind: "$field" (or the object form { path: "$field", ... }) is the syntax
- A document with an N-element array becomes N documents; each keeps every other field unchanged
- A document with a 0-length array or a missing field is dropped entirely by default
- The unwound field holds one element, not an array, in each output document
- $unwind is almost always followed by $match, $group, or $sort operating on the now-scalar field
- Input — { _id: 1, tags: ["a", "b", "c"] } — one document
- $unwind: "$tags" — the array field is exploded
- Output — { _id: 1, tags: "a" }, { _id: 1, tags: "b" }, { _id: 1, tags: "c" } — three documents
Command
{ $unwind: "$field" } or { $unwind: { path: "$field", preserveNullAndEmptyArrays, includeArrayIndex } }$unwind turns one document with an N-element array into N documents, each holding one element — and silently drops documents whose array is empty or missing, unless preserveNullAndEmptyArrays is set.