Search code examples
rubyarraysmongodbmongoidupdate-all

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


Solution

  • 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.