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

41

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The year was a typo. Thanks very much for the detailled explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.