Question

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))
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top