Arrays & Nested Documents
Querying Nested Fields
Dot notation into embedded documents, and why a missing path simply does not match.
IntermediateAbout 5 minutes
An embedded document is a field whose value is an object. You query inside it with dot notation. This is not an array yet — one object, named paths.
{
name: "Rahul",
city: "Bangalore",
address: {
line1: "Indiranagar",
city: "Bangalore",
pin: "560001"
}
}db.users.find({ "address.city": "Bangalore" })
db.users.find({ "address.pin": { $exists: true } }){ name: "Rahul", city: "Bangalore", address: { line1: "Indiranagar", city: "Bangalore", pin: "560001" } }{ address: { city: "Bangalore" } }means the entireaddressvalue equals that object —line1andpinwould make it miss. Dot notation is 'this path', not 'replace the object'.- A missing path does not match. No
address, oraddresswithoutcity, and{ "address.city": "Bangalore" }skips the document. Same rule as a missing top-level field. cityon the user andaddress.cityare different fields. They can disagree.
Interview question
How do you query a field inside an embedded document?
Think about it first.
Dot notation: { "address.city": "Bangalore" }. Matching { address: { city: "Bangalore" } } requires the whole subdocument to equal that object, so extra fields on address cause a miss.