Mongodb/Mongoid - what does {:multi => true} mean

主宰稳场 提交于 2019-12-08 01:38:43

问题


Regarding this question: With Mongoid, can I "update_all" to push a value onto an array field for multiple entries at once?

I would like to ask:

  1. What's the purpose of {:multi => true} here?
  2. Is it possible to push a value into an array when update_all via mongoid now? because the question is in 2010.

Thanks.


回答1:


The documentation for the MongoDB update method states the following:

multi - indicates if all documents matching criteria should be updated rather than just one. Can be useful with the $ operators below.

So basically the multi parameter is what enables the update_all behaviour in the question you linked to.

In answer to your second question: yes - Mongoid has this feature built in now. The documentation reference is here. But you can use it like this:

User.where(:gender => "Male").update_all(:title => "Mr")

Update

In the case where you want to push a value onto an array field, you'll still need to use the MongoDB library directly, since the Mongoid update_all method only supports the $set database update method (which can be used to update an entire array, but not push values onto it).

The example in the answer to the question you linked to would work, I have copied it below those who stumble across this question (thanks shingara!):

User.collection.update( 
  {'$in' => {:gender => 'Male'}}, 
  {'$push' => {:titles => 'Mr'}},
  {:multi => true}
)



回答2:


A particular usecase is when the Mongodb is sharded (http://docs.mongodb.org/master/MongoDB-sharding-guide.pdf). Specifically on update over a sharded mongo collection,when I used an identifier other than _id, the update failed. I had to set multi as true and then it updated all the documents across various shards.



来源:https://stackoverflow.com/questions/10102942/mongodb-mongoid-what-does-multi-true-mean

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