有没有办法在ReactiveMongo上执行批量更新?

时间:2014-08-18 21:35:34

标签: scala reactivemongo

假设我想要执行以下操作(在mongo shell中):

var bulk = db.vectors.initializeOrderedBulkOp()

bulk.find({"_id" : ObjectId("53f265da13d3f885ed8bf75d")}).updateOne({"$pop": {"v": 1}})

bulk.find({"_id" : ObjectId("53f265da13d3f885ed8bf75d")}).updateOne({"$push": {"v": 5}})

bulk.execute()

2 个答案:

答案 0 :(得分:5)

我找到了答案! ReactiveMongo具有RawCommand命令,允许我们运行任何MongoDB命令(如更新,在本例中为>>> http://docs.mongodb.org/manual/reference/command/update/#dbcmd.update):

  val commandDoc =
        BSONDocument(
          "update" -> COLLECTION,
          "updates" -> BSONArray(
            BSONDocument("q" -> <query>, "u" -> BSONDocument("$pop" -> BSONDocument("v" -> 1))),
            BSONDocument("q" -> <query>, "u" -> BSONDocument("$push" -> BSONDocument("v" -> 5)))
          ),
          "ordered" -> true
        )

      // we get a Future[BSONDocument]
      val futureResult = db.command(RawCommand(commandDoc))

      futureResult.map { result => // result is a BSONDocument
           //...
      }

答案 1 :(得分:2)

我正在使用reactive-mongo 0.11.9:

import collection.BatchCommands._
import UpdateCommand._ 
import reactivemongo.bson._

collection.runCommand(Update(
  UpdateElement(q = document(...), u = document(...)), 
  UpdateElement(q = document(...), u = document(...))...
))