skip to Main Content

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?

2

Answers


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

    Login or Signup to reply.
  2. $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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search