With Mongoid, can I "update_all" push a value into an array field for multiple records at once?

Using Mongoid, is it possible to use "update_all" to enter a value in an array field for all records that meet 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 am wondering if there is a way to update all users at once (to display the value "my_new_val" in the "foo" field for each corresponding record) using "update_all" (or something similar), instead of going through so that they update them one by one. I tried everything I could think of, and so far no luck.

thank

+5
source share
1 answer

You need to call 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}
)

pull_request , , Mongoid .

+5

All Articles