I’ll introduce search conditions for deeply nested fields in MongoDB.
Assume the following object is stored in the users collection:
{
"username" : "bob",
"address" : {
"street" : "123 Main Street",
"city" : "Springfield",
"state" : "NY"
}
}
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" })
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.