使用Mongoid,我可以“update_all”一次将值推送到多个条目的数组字段吗?

使用Mongoid,是否可以使用“update_all”将值推送到符合特定条件的所有条目的数组字段?

例:

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 

我想知道是否有办法立即更新所有用户(将值’my_new_val’推送到每个匹配条目的“foo”字段)使用“update_all”(或类似的东西)而不是循环通过它们来更新他们一次一个。 我已经尝试了所有我能想到的东西,到目前为止还没有运气。

谢谢

您需要从Mongo DB Driver调用它。 你可以做 :

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

要么

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

如果你想在Mongoid内置中,你可以执行pull_request或function请求。