mongodbmongoid5

Mongoid 'set' value in nested hash


I got the following document

{ a: { b: { c1: 1, c2: 2 } } }

I want to atomically modify only c1 to 8

I do document.set('a.b.c1': 8), but entire value of 'b' changes to {c1:8}.

this is my class

class C
  include Mongoid::Document
  field :a, type: Hash 
end

why is that?


Solution

  • It seems to be a bug in Mongoid 5 (as found by Neil). Here's how you can sidestep this for now (until you upgrade):

    C.where(id: object_id).update('a.b.c1' => 5)
    

    There's an alternative workaround in the linked jira ticket.