Mongodb merge using 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 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 .

There is no way to specify the name of the target collection dynamically and here is why:

We determine RBAC aka permissions (whether you have access to a particular collection or not) during parsing of the pipeline. If the into collection was specified dynamically there would be two problems, one of which is we would have to check permissions while running the aggregation. In addition, what if each document had a different value of that dynamic field and had to be merged into a different collection? That’s not really how $merge is meant to work.



This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.