使用ReactiveMongo和Scala备份许多记录

时间:2013-12-10 16:42:39

标签: scala akka upsert reactivemongo

我正在为使用ReactiveMongo的MongoDB编写一个DAO Actor。我想实现一些非常简单的CRUD操作,其中包括一次拍摄多个记录的能力。由于我有一个被动应用程序(基于Akka构建),因此对我来说很重要的是有幂等操作,因此我需要将操作设置为upsert而不是insert。

到目前为止,我有以下(丑陋)代码:

case class UpsertResult[T](nUpd: Int, nIns: Int, failed: List[T])

def upsertMany[T](l: List[T], collection: BSONCollection)
  (implicit ec: ExecutionContext, w: BSONDocumentWriter[T]):
    Future[UpsertResult[T]] = {
      Future.sequence(l.map(o => collection.save(o).map(r => (o, r))))
        .transform({
          results =>      
            val failed: List[T] = results.filter(!_._2.ok).unzip._1
            val nUpd = results.count(_._2.updatedExisting)
            UpsertResult(nUpd, results.size - nUpd - failed.size, failed)
        }, t => t)
      }    

是否有单独使用reactivemongo API一次性插入多条记录的方法?

我是一名MongoDB初学者,所以对许多人来说这听起来可能微不足道。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:3)

Mongo不支持在一个查询中插入多个文档。例如,更新操作总是只能插入一个新元素。因此,这不是reactivemongo驱动程序中的缺陷,根本没有DB命令来实现您期望的结果。迭代你想要插入的文件是正确的方法。

mongodb关于upsert的手册包含更多信息:

http://docs.mongodb.org/manual/core/update/#update-operations-with-the-upsert-flag

答案 1 :(得分:0)

根据文档BSSONCollection.save inserts the document, or updates it if it already exists in the collectionsee here。现在,我不确定如何决定文档是否已经存在:大概是基于MongoDB所说的...所以主键/ id或唯一索引

简而言之:我认为你是以正确的方式做到的(包括你的结果来自LastError)。