简体   繁体   中英

MongoDB using an array of IDs from one Collection to filter the results based on the IDs from another Collection

Suppose there is a MongoDB Collection CollA . Say CollA has the following three Documents:

{"_id": "1", "name": "Bob"},
{"_id": "2", "name": "John"},
{"_id": "3", "name": "Will"}

Let's say there is another MongoDB Collection CollB which has the following Document:

{
    "_id": "1", 
    "foo": {
        "arr": ["1", "3"]
    }
}

Is there a way in MongoDB to query CollB for the foo.arr array contents ( ["1"],["3"] ) and use it to retrieve the Documents in CollA which have these _id values, to produce the following result:

{"_id": "1", "name": "Bob"},
{"_id": "3", "name": "Will"}

Perform a simple $lookup from CollB . Use $replaceRoot with the $lookup result after $unwind

db.CollB.aggregate([
  {
    "$lookup": {
      "from": "CollA",
      "localField": "foo.arr",
      "foreignField": "_id",
      "as": "collALookup"
    }
  },
  {
    "$unwind": "$collALookup"
  },
  {
    "$replaceRoot": {
      "newRoot": "$collALookup"
    }
  }
])

Here is the Mongo Playground for your reference.

Query

  • lookup _id field with array foo.arr and limit 1, we just care if joined (no need to save many documents to memory)
  • keep documents that joined (not empty results)
  • unset the results field

*this will keep from collA all the documents that their _id , are in any array in collB (if you want only for 1 specific document of collB i think starting from collB like ray's answer makes more sense, but add a $match also before the $lookup for the 1 member of collB)

Playmongo

collA.aggregate(
[{"$lookup": 
   {"from": "collB",
    "localField": "_id",
    "foreignField": "foo.arr",
    "pipeline": [{"$limit": 1}],
    "as": "results"}},
 {"$match": {"$expr": {"$ne": ["$results", []]}}},
 {"$unset": ["results"]}])

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