liveBook · Manning

Subdocument

As explained in MongoDB 8.0 in Action, Third Edition

A nested document is a document stored as a field value inside another document or as an element of an array.

A subdocument is a document stored as a field value inside another document or as an element of an array. Embedding related data can keep it together, reduce separate storage structures, and simplify retrieval. section 2.6 section 1.1

Query subdocuments according to how precisely the nested data must be matched:

  • Use dot notation to query a field inside a nested document, without matching the entire embedded structure. section 4.9
  • Avoid exact embedded-document matches when possible: they require every field and the same field order, so omitted or reordered fields prevent a match. section 4.9.2
  • Query fields across array elements with dot notation, target a known position with an index such as .0, or use $elemMatch when multiple conditions must apply to one element. section 4.9.3

Finding qualifying prices

For route documents containing a prices array, use db.routes.find({ "prices.price": { $gte: 1000 } }) to find any price of at least 1000. Use $elemMatch when one array element must satisfy several conditions together: db.routes.find({ prices: { $elemMatch: { class: "business", price: { $lt: 3000 } } } }). section 4.9.3

[
  {
    _id: ObjectId('661a252acf6203ef2a1db277'),
    airline: { id: 413, name: 'American Airlines', alias: 'AA',
➥iata: 'AAL' },
    src_airport: 'DFW',
    dst_airport: 'LAX',
    codeshare: '',
    stops: 1,
    airplane: '737',
    prices: [
      { class: 'business', price: 2600 },
      { class: 'luxury', price: 4500 }
    ]
  }
]

Inspect the route document structure, including the airline subdocument and prices array, before constructing nested-field queries. section 4.9

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines embedding, demonstrates dot-notation and array queries, and warns about exact matching without covering broader schema design.
Examples
Uses route documents with airline subdocuments and prices arrays to demonstrate nested-field, positional, exact, and multi-criteria queries.
What it assumes
Assumes familiarity with MongoDB documents, collections, and fields while establishing the nested-document structure from basic terminology.
What you can do after
Apply it via MongoDB queries using dot notation, positional paths, and $elemMatch for embedded documents and arrays.
How it connects
Connects the document-oriented data model, flexible schema, arrays, dot notation, and $elemMatch.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.