简体   繁体   中英

How to find document with a max field value and update it in one go (atomically)?

We can use a line like this to find doc with a max value

db.collection.find().sort({ _id: -1 }).limit(1)

but it is impossible to chain update operation and find -> update means two server call which I'd like to avoid.

Is there another way to find and update item in on operation?

Try this once.

db.collection.update({},
{
  "$set": {
    key: 3
  }
},
{
  sort: {
    _id: -1
  },
  upsert: true
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM