[MongoDB] Search Conditions for Deeply Nested Fields

Tadashi Shigeoka ·  Tue, July 3, 2018

I’ll introduce search conditions for deeply nested fields in MongoDB.

MongoDB | モンゴディービー

MongoDB Data Assumptions

Assume the following object is stored in the users collection:

{
  "username" : "bob",
  "address" : {
    "street" : "123 Main Street",
    "city" : "Springfield",
    "state" : "NY"
  }
}

Search Conditions for Deeply Nested Fields

Conditions That Retrieve

By specifying the target field using dot notation like “address.state” as the key, you can retrieve documents if the value matches:

db.users.find({ "address.state" : "NY" })

Conditions That Don't Retrieve

On the other hand, if you specify the find condition in object format instead of dot notation as follows, it won’t retrieve:

db.users.find({ "address": { "state" : "NY" })

The reason is that this condition checks if the entire nested field within the address field exactly matches { state : “NY” }.

So, if you align all the nesting below the address field as follows, it will retrieve:

db.users.find({
  "address" : {
    "street" : "123 Main Street",
    "city" : "Springfield",
    "state" : "NY"
  }
)

That’s all from the Gemba where I want to be careful about search conditions for nested fields in MongoDB.

Reference Information