MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Ottieni il valore di ritorno della funzione reactivemongo findAndUpdate

Prova questo:

case class Person(name: String, count: Int)

object Helpers { 
  def increaseCount(collection: BSONCollection): Future[Option[Int]] = {
    import collection.BatchCommands.FindAndModifyCommand.FindAndModifyResult
    implicit val reader = Macros.reader[Person]

    val resultFut: Future[FindAndModifyResult] = collection.findAndUpdate(
      BSONDocument("name" -> "James"),
      BSONDocument("$inc" -> BSONDocument("count" -> 1)),
      fetchNewObject = true,
      upsert = true
    )

    val updatedCountOpt = resultFut.map { r =>
      r.result[Person].map { p =>
        p.count
      }
    }

    updatedCountOpt
  }
}