way to update multiple documents with different values

一个人想着一个人 提交于 2019-12-23 06:53:38

问题


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

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