Snaker.Wood
Snaker.Wood

Reputation: 659

MongoDB: find element by array element

I am having the following issue. Generally I have a collection holding objects with the following structure:

{
    _id: ObjectId("4f941bb2e4b06c6af7f80a0d"),
    fooId: ObjectId("4f941bb2e4b06c6af7e50aff"), 
    barsIds: [ObjectId("4f941bb2f5606c6af7f80ff5"), ObjectId("4f941bbc3fb06c6af7f80ccf")]
}

What is the query to find all elements in the collection that contain a given id in the barsIds property ?

Is it something like:

db.collectionName.find({"barsIds" : [ { "$oid" : "5300c6ba4a5ce5614bcd5d9a"}]})

Upvotes: 0

Views: 55

Answers (2)

Shnkc
Shnkc

Reputation: 2158

This is exactly what you are looking for:

db.collectionName.find({"barsIds" : ObjectId("4f941bb2f5606c6af7f80ff5") })

This query looks for documents whose barsIds elements are given object id. Or if barsIds is an array, this query looks for docs whose barsIds elements contain given object id.

Upvotes: 1

Rafa Paez
Rafa Paez

Reputation: 4860

Try with something like this

db.collectionName.find({:barsIds => {"$in" => BSON::ObjectId("5300c6ba4a5ce5614bcd5d9a")}})

Upvotes: 0

Related Questions