Home > Blockchain >  MongoDB - Update entire object of entry if subset/field is max
MongoDB - Update entire object of entry if subset/field is max

Time:04-07

I have an entry that looks something like:

{
  rank: {
    score: 5,
    date: '2020-01-01'
  }
}

Let's say I wanted to update the rank object only if the new rank's score is higher than the existing one. For example, I have a new rank that looks like:

{
  score: 10,
  date: '2022-12-12'
}

I know that the $max operator exists, but I'm not sure how to use it so that if the new score is higher, also update the date field - otherwise, do not update date. In other words, date should only be updated if score is updated.

CodePudding user response:

You can just add that to the query condition of your update, that way if it doesn't matter, no document will match the update.

const newRank = { score: 10, date: '2022-12-12' }
db.collection.updateOne(
{ 
  'rank.score': {$lt: newRank.score},
   // whatever else needs to be here
},
{
  $set: {
    rank: newRank
  }
})
  • Related