MongoDB: updating a subdocument in an array using an index

I have a document structured like this:

{ 
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 of them are cases where sub-documents have unique identifiers. I also found out how to reference one of the subdocuments by index, for example. to update the q field on the 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 instead of the index of array 0 above. I tried to create a local var with the correct string value and use it instead of "main.0.q" above, but this does not work. Any ideas?

+3
source share
1 answer

@JohnnyHK, , , , . , , , .

JohnnyHK, , , :

    var setModifier = { $set: {} };

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

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

, JohnnyHK!

+1

All Articles