Sambit
Sambit

Reputation: 454

Updating an array field that contains hashes in mongoid

I have a document in XYZ collection as follows.

"_id" : ObjectId("55311e4487216d7063040000"),
"colours" : [
    {
         "value" : 1,
         "colour" : "red"
    },
    {
         "value" : 2,
         "colour" : "green"
    }
]

I need to update the name of the colour which value is 1. What query should I write?

I am using rails 4.1.2, mongoid 4.0.0.

Please help.

Upvotes: 1

Views: 626

Answers (1)

Maxim Pontyushenko
Maxim Pontyushenko

Reputation: 3053

For example you want to change it to "yellow" :

XYZ.where(_id: "55311e4487216d7063040000").elem_match(colours: { value: 1 }).update("$set" => {"colours.$.colour" => "yellow"})

Upvotes: 7

Related Questions