2

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.

1 Answer 1

2

Try this one:

coll.update({ :id = > id }, { '$set' => {
    "evaluators.#{evaluator_name}" => {
        'adequacy' => adequacy, 'fluency' => fluency
    }
}})
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.