Skip to content

Arrays & Nested Documents

Nested Arrays

Arrays of documents that themselves contain arrays — and how far filters can reasonably go.

AdvancedAbout 7 minutes

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"] }
  ]
}
Products with tag lists on each variant — already uncomfortable
db.products.find({
  variants: {
    $elemMatch: {
      tags: { $all: ["wireless", "brown"] }
    }
  }
})
$elemMatch: a variant that is both wireless and 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.tags means 'any variant, any tag' — the same any-element rule, one level down.
  • Updates need arrayFilters on each level (variants.$[v].tags) or you $set a 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?

Think about it first.