Home > Back-end >  MongoDB $merge with two fields being unique before insert?
MongoDB $merge with two fields being unique before insert?

Time:01-19

Say I have a collection of elements with several fields, including userId and questionId. If I'm in an aggregation pipeline and I have a list of documents that all have userId and questionId as fields, but their values might already be in the collection (ie. a document of

{userId:1, questionId:1, score: 1}

but a similar document already exists in the collection

{userId:1, questionId:1, score:0}

How do I do a $merge into the collection while checking both fields? The $merge function does have an 'on: [field]' field to check overlap, but I don't think it can check two.

CodePudding user response:

You can specify multiple fields in the on clause using an array.

db.toBe.aggregate([
  {
    "$merge": {
      "into": "asIs",
      "on": [
        "userId",
        "questionId"
      ],
      "whenMatched": "merge"
    }
  }
])

Mongo Playground

  • Related