Home > database >  How to update document if it exist and insert it if it doesn't exist in mongodb?
How to update document if it exist and insert it if it doesn't exist in mongodb?

Time:11-07

This question is different from other similar questions because { upsert: true } option doesn't give desired output. I want to update/insert the given below document:

{
  _id: { 
    playerId: '1407081',
    tournamentId: '197831',
    matchId: '1602732' 
  },
  playerName: 'abcd',
  points: -5
}

After executing the given below code,

await Points.findOneAndUpdate(
  {
    "_id": playerStatsObjForDB._id
  }, 
  {
    playerStatsObjForDB
  }, 
  {
    upsert: true
  }
);
//where playerStasObjForDB is same as object mentioned in top.

if the document doesn't exist, it inserts the following document:

{
  "_id": {
    "playerId":"1407081",
    "tournamentId":"197831",
    "matchId":"1602732"
  },
  "__v":0,
}

I am using mongoose, but any help is greatly appreciated.

CodePudding user response:

Well MongoDB upsert works in the following way:

    db.products.updateMany(
    { _id: 6 },
    { $set: {price: 999} },
    { upsert: true}
)

So basically the first parameter is the query itself the same way you did, but the second one should be the updates you want to modify and you should use MongoDB operators like $set. Instead, it seems that you embedded the entire object inside it without modifications.

  • Related