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.
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.
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>, ... } }
You can match against array fields like admins
the same as you would a non-array field:
db.coll.find({admins: ObjectId("50ae3bdb50b3d6f014000279")})
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