Question

I have nested data:

Object
_id: "90fac6ab-b88e-42a1-8e91-80ee25951ec7"
  answers: Array[4]
    0: Object
      name: "myData"
      owned_by: "273b7291-df2b-494c-bd9b-64e71283447e"
      score: 0

I am trying to update, only a specific nested answer whose name I know. I would simply like to increment the score field, and I only know name. How does one accomplish this?

Thus far I have this: db.Question.update({_id: "90fac6ab-b88e-42a1-8e91-80ee25951ec7"}, "myData":{$inc: {score: 2}});

Was it helpful?

Solution

You are looking to increment the score of each answer based on the name of the answerer (I assume that's what name is) as such:

db.Question.update({
    _id: "90fac6ab-b88e-42a1-8e91-80ee25951ec7", 
    answers.name : "myData"
}, {$inc: {"answers.$.score": 1}})

Should work. I use the positional operator here to reach into a suboducment to populate the $: http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator

OTHER TIPS

Try this;

db.Question.update({ _id: "90fac6ab-b88e-42a1-8e91-80ee25951ec7", "answers.name": "myData" }, 
                   { $inc: { "answers.$.score": 2} });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top