ReactiveMongo: How to use FindAndModify to read a document and increment a value atomically

StackOverflow https://stackoverflow.com/questions/21522990

  •  06-10-2022
  •  | 
  •  

Frage

I need to read a document and increment a value atomically. I know ReactiveMongo provides FindAndModify and looked at this example. If you look at the findAndModify method in the example, you'll see that it just finds the documents that match a condition and then updates them with a new value.

How do I set a new value based on the old one? In other words, I need to read a value, increment it, and eventually update the document [atomically]:

def incrementValue() = {
  val selector = BSONDocument("name" -> "Joe")
  val modifier = BSONDocument(
    "$set" -> BSONDocument("version" -> ???)) // how do I increment the old
                                              // value of 'version' by 1? 
  val command = FindAndModify(
    collection.name,
    selector,
    Update(modifier, false))
War es hilfreich?

Lösung

Use $inc instead of $set. Here you can find the documentation. Of course it also works with findAndModify.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top