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

狂风中的少年 提交于 2019-12-23 09:41:42

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/9637728/with-mongoid-can-i-update-all-to-push-a-value-onto-an-array-field-for-multipl

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