MongoDB - 如何原子地增加一个数字并获得新值

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

基本上我需要在文档中增加一个计数器并获取新值,但这必须以原子方式工作。

目前我正在使用命令:

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

但是我找不到如何立即获得新的增量值。

updateOne 不return 文档/文档字段。

你想做的是使用findOneAndUpdate。现在这仍然是 return 的“旧”文档,因此您想指定 returnOriginal: false

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