scalareactivemongo

What is the way of using transaction with ReactiveMongo?


I am trying to use transaction with reactivemongodb in playframework. How can I do this or is there any documentation available for playframework ?


Solution

  • In the documentation you can find example how to use MongoDB >4 transactions.

    import scala.concurrent.{ ExecutionContext, Future }
    
    import reactivemongo.bson.BSONDocument
    
    import reactivemongo.api.DefaultDB
    
    def testTx(db: DefaultDB)(implicit ec: ExecutionContext): Future[Unit] = 
      for {
        dbWithSession <- db.startSession()
        dbWithTx <- dbWithSession.startTransaction(None)
        coll = dbWithTx.collection("foo")
    
        _ <- coll.insert.one(BSONDocument("id" -> 1, "bar" -> "lorem"))
        r <- coll.find(BSONDocument("id" -> 1)).one[BSONDocument] // found
    
        _ <- db.collection("foo").find(
          BSONDocument("id" -> 1)).one[BSONDocument]
          // not found for DB outside transaction
    
        _ <- dbWithTx.commitTransaction() // or abortTransaction()
          // session still open, can start another transaction, or other ops
    
        _ <- dbWithSession.endSession()
      } yield ()