Hi @Cyril_Auburtin1,

The deleted field is removed from collection a, but it already exists in collection b. When merging, the $merge stage will not automatically remove fields from the destination collection (b). To address this, you can use the whenMatched property in the $merge stage to handle the removal of the deleted field during the merge.

In this case, you don’t need the $replaceRoot or $unset stages. Instead, you can simplify the pipeline by starting with a $project stage to shape the documents from collection a, and then use $merge with whenMatched to update and remove the deleted field in collection b.

Here’s the refined solution:

await conn.collection('a').aggregate([
  { 
    "$project": { 
      "_id": "$bid", 
      "name": 1 
    }
  },
  {
    "$merge": {
      "into": "b",
      "whenMatched": [
        {
          "$set": {
            "name": "$name", 
            "deleted": "$$REMOVE" 
          }
        }
      ],
      "whenNotMatched": "discard" 
    }
  }
]).toArray();
2 Likes