Reputation: 6808
I'm trying to update a hash that's nested in a MongDB document.
I know about the $push
function for arrays, and $set
for completely overwriting elements, but I can't quite get the behaviour I'm looking for.
Here's what I'm trying to get:
Before:
{
'id' => 1234,
'evaluators' => {
'A' => { 'x' => 2, 'y' => 4 },
}
}
Expected, after:
{
'id' => 1234,
'evaluators' => {
'A' => { 'x' => 2, 'y' => 4 },
'B' => { 'x' => 3, 'y' => 5 },
}
}
I've tried doing (in Ruby):
coll.update({ :id => id },
{ '$set' => {
'evaluators' => {
evaluator_name => { 'adequacy' => adequacy,
'fluency' => fluency }
}
} } )
But it overwrites the contents of my evaluators
hash and I end up with:
{
'id' => 1234,
'evaluators' => {
'B' => { 'x' => 3, 'y' => 5 },
}
}
I could do a query to load the entire document into Ruby, change the data and re-insert it to the DB but I was wondering if there was a better way that I don't know about.
Upvotes: 2
Views: 1334
Reputation: 47618
Try this one:
coll.update({ :id = > id }, { '$set' => {
"evaluators.#{evaluator_name}" => {
'adequacy' => adequacy, 'fluency' => fluency
}
}})
Upvotes: 2