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
