问题
I am using mongoid 3.1 with Ruby 1.9.3 and I am trying to update a value within an array. I can successfully perform the following command in mongodb's CLI, but can't seem to find the appropriate solution/translation for mongoid.
user.update( { activities: { $elemMatch: { uuid: "1111111-xxxx-xxxx" }}}, { $set: { 'activities.$.submitted': true }})
For context the document looks like:
{
"_id" : ....,
"user_name" : "bob",
"activities: [
{
uuid: "1111111-xxxx-xxxx",
submitted: true,
},
{
uuid: "222222-xxxx-xxxx",
submitted: false,
},
{
uuid: "333333-xxxx-xxxx",
submitted: false,
}
]
}
The goal is to change submitted to true based on the uuid value. From what I can tell, all of the "updating" solutions in mongoid only deal with the attributes at the root of the document and can't have options for the $ positional operator.
Any help would be appreciated.
Thank you
回答1:
Looks like I found the answer in a github issue discussion.
The solution for me was:
User.elem_match(activities: { type: "redemption" }).elem_match(activities: { uuid: uuid }).update("$set" => {"activities.$.submitted" => true })
来源:https://stackoverflow.com/questions/18346287/mongoid-update-elements-within-array