Home > database >  Upsert many documents based on _id
Upsert many documents based on _id

Time:10-06

I need to upsert many documents based on _id.

E.g.
document_1 = {_id:"1", "age":11, "name":"name1"}
document_2 = {_id:"2", "age":22, "name":"name2"}

I wrote the below

db.my_collection.updateMany(
    { _id: {"$in":["1","2"] } },
    [
        {$set: {_id:"1", "age":11, "name":"name1"}},
        {$set: {_id:"2", "age":22, "name":"name2"}}
    ],
    true
    )

But no rows gets updated or inserted. Where have I gone wrong?

CodePudding user response:

Instead of true in the 3rd parameter, you have to pass {new: true, upsert: true}.

CodePudding user response:

$merge seems to be a better option for upsert operation. You can store the records you want to upsert in another collection, says to_be_inserted and perform $merge in the aggregation pipeline.

db.to_be_upserted.aggregate([
  {
    "$merge": {
      "into": "my_collection",
      "on": "_id",
      "whenMatched": "merge",
      "whenNotMatched": "insert"
    }
  }
])

Here is the Mongo Playground for your reference.

  • Related