Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using Mongoid, is it possible to use "update_all" to push a value onto an array field for all entries matching a certain criteria?

Example:

class Foo
  field :username
  field :bar, :type => Array

  def update_all_bars
    array_of_names = ['foo','bar','baz']
    Foo.any_in(username: foo).each do |f|
      f.push(:bar,'my_new_val')
    end
  end
end

I'm wondering if there's a way to update all the users at once (to push the value 'my_new_val' onto the "foo" field for each matching entry) using "update_all" (or something similar) instead of looping through them to update them one at a time. I've tried everything I can think of and so far no luck.

Thanks

like image 269
orderedchaos Avatar asked Mar 09 '12 16:03

orderedchaos


1 Answers

You need call that from the Mongo DB Driver. You can do :

Foo.collection.update( 
  Foo.any_in(username:foo).selector, 
  {'$push' => {bar: 'my_new_val'}},
  {:multi => true}
)

Or

Foo.collection.update( 
  {'$in' => {username: foo}}, 
  {'$push' => {bar: 'my_new_val'}},
  {:multi => true}
)

You can do a pull_request or a feature request if you want that in Mongoid builtin.

like image 76
shingara Avatar answered Nov 09 '22 10:11

shingara