Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Subdocument in Array with mongodb

Tags:

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?

like image 437
mritz_p Avatar asked Oct 28 '13 10:10

mritz_p


People also ask

How do I find an element in an array in MongoDB?

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.

Where can I find nested documents in MongoDB?

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.

How do I filter an array of objects in MongoDB?

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.

How do I find a specific data in MongoDB?

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.


1 Answers

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.

like image 146
mnemosyn Avatar answered Oct 20 '22 06:10

mnemosyn