使用ReactiveMongo和Scala更新许多记录 [英] Upsert many records using ReactiveMongo and Scala

查看:165
本文介绍了使用ReactiveMongo和Scala更新许多记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为使用ReactiveMongo的MongoDB编写DAO Actor。我想实现一些非常简单的CRUD操作,其中包括一次可以增加许多记录的功能。由于我有一个响应式应用程序(基于Akka构建),因此对我来说,进行幂等操作很重要,因此我需要使该操作成为upsert而不是insert。

I am writing a DAO Actor for MongoDB that uses ReactiveMongo. I want to implement some very simple CRUD operations, among which the ability to upsert many records in one shot. Since I have a reactive application (built on Akka), it's important for me to have idempotent actions, so I need the operation to be an upsert, not an insert.

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

So far I have the following (ugly) code to do so:

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)
      }    

是否存在仅使用reactmongo API一次即可增加许多记录的简便方法?

Is there an out-of-the-box way of upserting many records at once using the reactivemongo API alone?

我是MongoDB初学者,所以对许多人来说听起来微不足道。谢谢您的帮助!

I am a MongoDB beginner so this might sound trivial to many. Any help is appreciated!

推荐答案

Mongo不支持在一个查询中上载多个文档。例如,更新操作始终只能最多插入一个新元素。因此,这不是reactmongo驱动程序中的缺陷,根本没有DB命令可实现您期望的结果。遍历要升级的文档是正确的方法。

Mongo has no support for upserting multiple documents in one query. The update operation for example can always only insert up to one new element. So this is not a flaw in the reactivemongo driver, there simply is no DB command to achieve the result you expect. Iterating over the documents you want to upsert is the right way to do it.

mongodb上有关升级的手册包含更多信息:

The manual on mongodb about upsert contains further informations:

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

这篇关于使用ReactiveMongo和Scala更新许多记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆