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?
To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.
Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.
Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.
Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With