mongodbscalareactivemongo

In ReactiveMongo 0.18.8, how can I perform an update of several documents, with different values, in a single command?


I found this answer whilst digging in SO.

Basically, this is exactly what I need. However, it appears that in my current version of ReactiveMongo, which is 0.18.8, db.command(RawCommand(commandDoc)) is no longer possible. There is no "command" under DB. I can't seem to find where this command moved.

Can anyone please help me? Or maybe tell me how else I can implement what I need?

I am trying to perform several updates, of several documents with different values, in a single DB command.

Thanks!


Solution

  • In the documentation you can see example of bulk operations to insert, update or delete.

    import scala.concurrent.Future
    import scala.concurrent.ExecutionContext.Implicits.global
    
    import reactivemongo.api.bson.BSONDocument
    
    import reactivemongo.api.bson.collection.BSONCollection
    
    def updateWithBulk(personColl: BSONCollection) = {
      // Bulk update: multiple update
      val updateBuilder1 = personColl.update(ordered = true)
      val updates = Future.sequence(Seq(
        updateBuilder1.element(
          q = BSONDocument("firstName" -> "Jane", "lastName" -> "Doh"),
          u = BSONDocument("age" -> 18),
          upsert = true,
          multi = false),
        updateBuilder1.element(
          q = BSONDocument("firstName" -> "Bob"),
          u = BSONDocument("age" -> 19),
          upsert = false,
          multi = true)))
    
      updates.flatMap { ops => updateBuilder1.many(ops) }
    }
    

    Also note that version 0.18.8 is about one year old, latest version being the major release 1.0.0.