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
Instead of
true
in the 3rd parameter, you have to pass{new: true, upsert: true}
.$merge
seems to be a better option for upsert operation. You can store the records you want to upsert in another collection, saysto_be_inserted
and perform$merge
in the aggregation pipeline.Here is the Mongo Playground for your reference.