Skip to content

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"
  }
}
Rahul with an address object
db.users.find({ "address.city": "Bangalore" })
db.users.find({ "address.pin": { $exists: true } })
Quote the path. Equality and $gt work like they did on top-level fields.
{ name: "Rahul", city: "Bangalore", address: { line1: "Indiranagar", city: "Bangalore", pin: "560001" } }
  • { address: { city: "Bangalore" } } means the entire address value equals that object — line1 and pin would make it miss. Dot notation is 'this path', not 'replace the object'.
  • A missing path does not match. No address, or address without city, and { "address.city": "Bangalore" } skips the document. Same rule as a missing top-level field.
  • city on the user and address.city are different fields. They can disagree.

Interview question

How do you query a field inside an embedded document?

Think about it first.