xpepermint
xpepermint

Reputation: 36273

Rails+mongoid: update_all("position=position-1")?

Is this possible with Rails+Mongoid:

Model.update_all("position=position-1")

Upvotes: 1

Views: 787

Answers (3)

Dane
Dane

Reputation: 892

This works:

Model.all.inc(:position, -1)  

Upvotes: 0

Iwan B.
Iwan B.

Reputation: 4166

Sure you can! Without selection (update all collections):

Model.update_all(obsolete: false)

or with selection:

Model.where(:id.in => ids_array).update_all(obsolete: true)

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

While there's no direct equivalent to this idiom (set field to a some function of some fields of the document), there is a way to do this exact update.

Model.collection.update({},  # find all documents
                        {'$inc' => {:position => -1}}, # decrement position
                        :multi => true) # multi-update (update all)

This is using underlying mongodb driver to do the job. I don't know how to express this in Mongoid interface.

Upvotes: 2

Related Questions