Is there any way to join two mongo db collection with dynamic collection name?

343 views Asked by At

I created a ref collection which contains other collection name and document id.

So it looks like

{
   refName: "Collection 1",
   refId: "123123",
},
{
   refName: "Collection 2",
   refId: "456734",
}

Collection 1 and Collection 2 have the documents with id 123123 and 456734. In this case, I wanna loop all ref collection and get referenced collection data using mongodb aggregation.

I tried to use $lookup but it is said that $from of $lookup must be string literals, not the variables.

Is there anyway to handle this kind of transaction in MongoDB?

1

There are 1 answers

3
varman On

You can convert string to int or int to string

db.ref.aggregate([
  {
    $addFields: {
      refId: {
        "$toInt": "$refId"
      }
    }
  },
  {
    "$lookup": {
      "from": "coll1",
      "localField": "refId",
      "foreignField": "_id",
      "as": "join"
    }
  }
])

Working Mongo playground String to Int

Working Mongo playground Int to String withUncorrelated-sub-queries