skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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"]}])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search