ReactiveMongo Extensions: Bulk update using reactive mongo extensions

余生颓废 提交于 2020-01-06 19:30:06

问题


Is there any way to update bulk records. I am trying to update user object using following code:

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

In above code i am passing, users List. in user list i also add new properties and chage existing properties state, but with this statement the records are not update

If i am using following code:

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

The record updated successfully.


回答1:


From my reading of the API as well as other answers in this area, I don't think the kind of bulk update you're looking for is possible via the update method.

What you could do however, is issue a Raw Command (credit: this answer), which, if you are patient enough to write the all the $set expressions, would definitely work, and be more efficient than a client-side loop doing save() operations one-by-one:

Caution: compiles, but is untested:

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


来源:https://stackoverflow.com/questions/30377600/reactivemongo-extensions-bulk-update-using-reactive-mongo-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!