Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo: how to find by ObjectId that is stored in a subarray?

I have a collection with records like this:

{
    "_id" : ObjectId("50ae3bdb50b3d6f01400027a"),
    "admins": 
       [ObjectId("50ae3bdb50b3d6f014000279"), ObjectId("50ae3bdb50b3d6f01400027e")]
}

I would like to search by the the 'admin' array.

How can I find all documents included for example ObjectId("50ae3bdb50b3d6f014000279") in the sub-array.

Thank you.

like image 678
Tomas Randus Avatar asked Nov 22 '12 15:11

Tomas Randus


People also ask

How do you get a specific object from 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.

How do I query embedded files 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 query an array in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }


1 Answers

You can match against array fields like admins the same as you would a non-array field:

db.coll.find({admins: ObjectId("50ae3bdb50b3d6f014000279")})
like image 95
JohnnyHK Avatar answered Oct 17 '22 16:10

JohnnyHK