Con Mongoid, ¿puedo "actualizar_todos" para insertar un valor en un campo de matriz para varias entradas a la vez?

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

Ejemplo:

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.

Muchas Gracias

preguntado el 09 de marzo de 12 a las 16:03

1 Respuestas

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.

respondido 10 mar '12, 10:03

Was just writing the answer, there should also be a third parameter multi: true - basura

Qué es esto :multi => true ¿por? - larryzhao

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.