3

I have document structured like so:

{ 
key: "apples002",

main: [
         {q: "Is the apple green?", a1: "The apple is not green.", a2: "No."},

         {q: "What color is the apple?", a1: "The apple is yellow.", a2: "Yellow."}
      ],

alt: [

         {q: "What color is the apple?", a1: "The apple is red."},

         {q: "Is the apple yellow?", a1: “The apple is yellow.”, a2: “Yes.”}
     ]

}

I have seen several examples for updating sub-document fields, but most all of them are cases where the sub-documents have unique ids. I have also learned how to refer to one of the sub-documents by index, e.g. to update the q field on main above (first element):

myDB.update({key: 'apples002'}, {$set: {'main.0.q': 'Updated question goes here'}})

So in my case, I would like to use a variable in place of the array index 0 above. I have tried creating a local var with the correct string value and using it in place of 'main.0.q' above, but that doesn't work. Any ideas?

1

1 Answer 1

1

@JohnnyHK, you're right, it is essentially a duplicate. I tried and tried to find this info yesterday and couldn't do it, so I think it's not a bad idea to have this question around in a couple of forms.

I've adapted JohnnyHK's answer to show what I have to do to make the above update work with a variable for the index:

    var setModifier = { $set: {} };

    setModifier.$set['main.' + myIndex + '.q'] = 'Updated question goes here.';

    PL.update({key: 'apples002'}, setModifier);

Thanks, JohnnyHK!

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

1 Comment

I just went back and checked the official MongoDB and I didn't see anything about using $set in this way. Where do you find this stuff? Also, I assume you can't programmatically build a set modifier like this that updates more than one field? Not that I'm complaining, I'm just glad it's possible to use the index.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.