简体   繁体   中英

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"}]})

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.

试试这样的东西

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM