0

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}});

JZ.
  • 21,147
  • 32
  • 115
  • 192

2 Answers2

1

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

Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • Dang! You just beat me to it (poor train wifi). – cirrus Oct 30 '12 at 09:04
  • Is there any way to update the nested queried object using $set and passing an object only containing attributes to be updated? I mean something like this as second arg {$set : {"answers.$" : {attr1:val1, attr2:val2}}} – Giuliano Iacobelli Aug 22 '13 at 16:26
0

Try this;

db.Question.update({ _id: "90fac6ab-b88e-42a1-8e91-80ee25951ec7", "answers.name": "myData" }, 
                   { $inc: { "answers.$.score": 2} });
cirrus
  • 5,624
  • 8
  • 44
  • 62