问题
I have the following documents:
[{
"_id":1,
"name":"john",
"position":1
},
{"_id":2,
"name":"bob",
"position":2
},
{"_id":3,
"name":"tom",
"position":3
}]
In the UI a user can change position of items(eg moving Bob to first position, john gets position 2, tom - position 3). Is there any way to update all positions in all documents at once?
回答1:
You can not update two documents at once with a MongoDB query. You will always have to do that in two queries. You can of course set a value of a field to the same value, or increment with the same number, but you can not do two distinct updates in MongoDB with the same query.
回答2:
You can use db.collection.bulkWrite() to perform multiple operations in bulk. It has been available since 3.2
.
It is possible to perform operations out of order to increase performance.
来源:https://stackoverflow.com/questions/17207183/way-to-update-multiple-documents-with-different-values