How to query nested objects?

Edmondo1984 picture Edmondo1984 · Apr 14, 2013 · Viewed 182k times · Source

I have a problem when querying mongoDB with nested objects notation:

db.messages.find( { headers : { From: "[email protected]" } } ).count()
0
db.messages.find( { 'headers.From': "[email protected]" }  ).count()
5

I can't see what I am doing wrong. I am expecting nested object notation to return the same result as the dot notation query. Where am I wrong?

Answer

shx2 picture shx2 · Apr 14, 2013

db.messages.find( { headers : { From: "[email protected]" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "[email protected]" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs