How to query nested objects?

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

db.messages.find( { headers : { From: "reservations@marriott.com" } } ).count()
0
db.messages.find( { 'headers.From': "reservations@marriott.com" }  ).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?


db.messages.find( { headers : { From: "reservations@marriott.com" } } )

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


db.messages.find( { 'headers.From': "reservations@marriott.com" } )

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


Dot-notation docs


The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (ie, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street' , in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});
链接地址: http://www.djcxy.com/p/86406.html

上一篇: 如何用MID查询mongodb

下一篇: 如何查询嵌套对象?