17

I have a model

class Employee
  include Mongoid::Document
  field :first_name
  field :last_name
  field :address1
  field :address2
  field :salary
end

Now I need to update all Employee's salary to 10000 whose address1 is "Calgary"

Now I tried this query

Employee.update_all "salary = 10000", "address1 = 'Calgary'"

But this query gave me error as:

NoMethodError: undefined method `update_all' for Employee:Class

Thanks

Peter Brown
  • 50,956
  • 18
  • 113
  • 146
Gagan
  • 4,278
  • 7
  • 46
  • 71

3 Answers3

41

You should try to update your MongoID to latest version. Mongoid 2.0 was released sometime back. I guess update_all, destroy_all and delete_all got introduced in one of the rc's.

After upgrade, following should work

Employee.where(:address1 => 'Calgary').update_all(:salary => 10000)
rubish
  • 10,887
  • 3
  • 43
  • 57
  • 7
    AFAIK the gotcha is that `update_all` is a method on a ResourceList (array of results) and not on the model itself. So you can not call Foo.update_all, but you can call Foo.some_selection.update_all. – berkes Apr 12 '11 at 19:53
  • @berkes: you can get "empty" selection by using `Foo.scoped.update_all` – Sergio Tulentsev Aug 27 '15 at 09:13
0

A more up to date way to do it using Moped (the underlying driver):

Employee.collection.find(address1: 'Calgary').update_all(salary: 10000)

Weird query BTW :P

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
Fabiano Soriani
  • 8,182
  • 9
  • 43
  • 59
0

According to this http://groups.google.com/group/mongoid/browse_thread/thread/ac08564d5a38da13?pli=1

and a quick Model.respond_to?(:update_all) outputs true, suggests that Model.update_all is fine

Khoa Nguyen
  • 1,540
  • 2
  • 15
  • 21