20

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?

1 Answer 1

40

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.

1
  • The year was a typo. Thanks very much for the detailled explanation!
    – mritz_p
    Commented Oct 28, 2013 at 11:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.