【问题标题】:ReactiveMongo Extensions: Bulk update using reactive mongo extensionsReactiveMongo Extensions:使用响应式 mongo 扩展进行批量更新
【发布时间】:2015-05-21 15:05:43
【问题描述】:

有没有办法更新批量记录。我正在尝试使用以下代码更新用户对象:

.update($doc("_id" $in (usersIds: _*)), users, GetLastError(), false , true)

在上面的代码中,我传递了users 列表。在用户列表中,我还添加了新属性并更改现有属性状态,但是使用此语句,记录不会更新

如果我使用以下代码:

.update($doc("_id" $in (usersIds: _*)), $set("inviteStatus" $eq "Invited"), GetLastError(), false , true)

记录更新成功。

【问题讨论】:

    标签: mongodb scala updates playframework-2.3 play-reactivemongo


    【解决方案1】:

    根据我对APIother answers 在这方面的阅读,我认为您正在寻找的那种批量更新不可能通过update 方法实现。

    可以做的是发出Raw Command(信用:this answer),如果你有足够的耐心写出所有$set表达式,肯定会工作,并且比进行save() 操作的客户端循环更高效:

    注意:编译,但未经测试:

    import reactivemongo.api.DB
    import reactivemongo.bson._
    import reactivemongo.core.commands.RawCommand
    
    class BulkUpdater(db:DB) {
    
      def bulkUpdateUsers(users:List[User]) = {
    
        def singleUpdate(u:User) = BSONDocument (
          ("q" -> BSONDocument("_id" -> u._id)),
          ("u" -> BSONDocument("$set" -> BSONDocument(
            "firstName" -> u.firstName, 
            "secondName" -> u.secondName) // etc
        )))
    
      val commandBson = BSONDocument(
        "update" -> "users",
        "updates" -> BSONArray(users.map(singleUpdate)),
        "ordered" -> false,
        "writeConcern" -> BSONDocument( "w" -> "majority", "wtimeout" -> 5000)
      )
    
      db.command(RawCommand(commandBson))
    }
    

    【讨论】:

    • 你好@millhouse,有没有办法为Json对象运行RawCommand
    • 应该可以将 RawCommand 的主体定义为 Play JsValue,然后使用 Play ReactiveMongo 库中的 BSONFormats 将其转换为 BSONDocument
    • 嘿@millhouse,这不适合我。以下是我的代码:` val commandJSON = BSONDocument("udapte" -> "users", "updates" -> BSONArray(users.map {userUpdateQueryDocument}), "ordered" -> false, "writeConcern" -> BSONDocument(" w" -> "多数") )`
    • 当我执行这段代码时`val doc = userCollection.db.command(RawCommand(commandJSON)) doc.map { bson => println(">>>>>>>>>>>> >>>>>>>>>>>>: "+bson) } ` println 语句没有运行
    • 我的代码通过以下异常:`reactivemongo.core.commands.DefaultCommandError: BSONCommandError['command faile d because the 'ok' field is missing or equals 0'] with original doc { `
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    相关资源
    最近更新 更多