ruby-on-railsrubyruby-on-rails-3mongoidmongoid3

Atomic inc of multiple mongoid hash values


I have a Mongoid model with a hash field that looks like this:

class DimensionStat
 include ::Mongoid::Document
 include ::Mongoid::Timestamps

 field :data, type: Hash

 attr_accessible :data
end

I pretend on runtime fill data with something like

data: {
    'a' => 1,
    'b' => 2,
    ...
}

I need to perform increments on multiple keys atomically such as:

'a' => -1,
'b' => 5

Somewhere I found that:

instance.collection.find(_id: my_id).update("$inc" => {'data.a' => -1,
'data.b' => 5})

will do the trick but it doesn't, what am I doing wrong?

UPDATE: I'm using mongoid 3.1.6


Solution

  • The .inc method works perfectly with non-existing keys, but the document is not automatically refreshed from the database. Try:

    dimension_stat.inc('data.a' => -1, 'data.b' => 5)
    puts dimension_stat.data['a'] # not changed
    dimension_stat.reload
    puts dimension_stat.data['a'] # changed
    

    you will see that the counters have changed.