6

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.

Community
  • 1
  • 1
larryzhao
  • 3,173
  • 2
  • 40
  • 62

2 Answers2

7

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}
)
Community
  • 1
  • 1
theTRON
  • 9,608
  • 2
  • 32
  • 46
  • Thanks @theTRON, for question 2: you showed to update a plain field, is it also possible to use it to push a value into an array field? – larryzhao Apr 11 '12 at 13:42
  • The Mongoid docs mention that it uses the `$set` method - which sets the value of a field. So you'll have to the MongoDB library - i've updated my answer to reflect this. – theTRON Apr 11 '12 at 14:03
  • Thanks, so that means is still using this way. :) – larryzhao Apr 11 '12 at 14:35
1

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.

user2725012
  • 61
  • 1
  • 5