Arrays & Nested Documents
Nested Arrays
Arrays of documents that themselves contain arrays — and how far filters can reasonably go.
A review with comments, an item with tags, a department with teams of members. Nested arrays are legal. They are also where queries stop being something you want in a hot path.
{
name: "Mechanical Keyboard",
variants: [
{ sku: "KB-BRN", tags: ["wired", "brown"] },
{ sku: "KB-WLS", tags: ["wireless", "brown"] }
]
}db.products.find({
variants: {
$elemMatch: {
tags: { $all: ["wireless", "brown"] }
}
}
})Two levels of $elemMatch is the ceiling for most backends. Deeper than that, you are asking the database to search a tree. Prefer: flatten tags onto the product, keep variants in their own collection, or $unwind in an aggregation (later) when you are reporting, not serving a request.
- Dotted
variants.tagsmeans 'any variant, any tag' — the same any-element rule, one level down. - Updates need
arrayFilterson each level (variants.$[v].tags) or you$seta whole variant. - Unbounded nested arrays (comments on comments on comments) hit the 16MB document limit. Modelling covers that; do not grow a document as a thread.
Interview question
How far should you go with nested arrays in MongoDB?
An array of documents on the parent is the usual embed — order items. Arrays inside those, queried independently, get painful: stacked $elemMatch, arrayFilters at every level, document growth. I flatten or I reference another collection before I nest a third level.