Gagan
Gagan

Reputation: 4378

mongoid update all documents with conditions

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

Upvotes: 18

Views: 16145

Answers (3)

Fabiano Soriani
Fabiano Soriani

Reputation: 8562

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

Upvotes: 0

Khoa Nguyen
Khoa Nguyen

Reputation: 1600

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

Upvotes: 0

rubish
rubish

Reputation: 10907

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)

Upvotes: 41

Related Questions