'Mongodb merge using dynamic field value as collection name

I am trying to do merge stage in MongoDB aggregation pipeline to a target collection. The name for target collection in $merge stage needs to be passed using field value of document got from previous stage .

Below is my pipeline stage for merge that I am using . Here I need to pass a dynamic field ..'$sender_id' which is field value of document from prev stage … to ‘coll’ parameter of $merge but it is throwing this error :

PlanExecutor error during aggregation :: caused by :: Invalid collection name: $sender_id

  $merge: {
    into: {
      "db": "conversations_archive",
      "coll": "$sender_id"
    },
    on: "_id",
    // let: {sender_id: '$sender_id'},
    // whenMatched: 'keepExisting',
    // whenNotMatched: 'insert' }
  }

I tried using new operator as well as double dollar but none worked even $toString didn’t work .

Please help .

I tried using double operator , new operator $$new.sender_id , as well as $toString operator.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source