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