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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Dang! You just beat me to it (poor train wifi).
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}}}
0

Try this;

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.