简体   繁体   中英

Find Subdocument in Array with mongodb

I am playing around with the The bios Example Collection from http://docs.mongodb.org/manual/reference/bios-example-collection to educate myself about querying mongodb.

I want to retrieve informations about the awards won by _id : 1 in year : 1975 .

I tried several queries, among those

bios.find({
    "_id" : 1,
    "awards" : {
        "year" : 1975
    }
});

but I never receive the proper document back. How can I retrieve this document in the array?

You have to use the dot notation :

bios.find({"_id" : 1, "awards.year" : 1975 });

It's a rather pointless query, because you also have the _id in the query, but I guess that's due to the fact that you're playing with an example. Also, you're saying you're looking for awards from 1967, but the code says 1975.

If you search for "awards" : { "year" : 1975 } , mongodb will look for an exact match of the entire subdocument awards . In this case, that is not what you want. Also, since awards is an array, this will always be false. If you wanted to look up a specific award document in a list, $elemMatch would be the way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM