Search code examples
javascriptmongodbmongooseconcurrencytransactions

MongoDB - How to atomically increase a number and get the new value


Basically I need to increase an counter in an document and get the new value, but this has to work atomically.

Current I'm using the command:

.updateOne({_id: ObjectId('5ed7f23789bcd51e9c6a82e0')}, {$inc: {nextTicket: 1}})

But I can't find how to immediately get the new incremented value.


Solution

  • updateOne does not return the document / the documents fields.

    What you want to do is use findOneAndUpdate. now this still returns the "old" document so you want to specify returnOriginal: false

    .findOneAndUpdate({_id: ObjectId('5ed7f23789bcd51e9c6a82e0')}, {$inc: {nextTicket: 1}}, {returnOriginal: false})