Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Update a sub-document in an array using an index

Tags:

arrays

mongodb

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?

like image 590
Michael McC Avatar asked Feb 19 '26 12:02

Michael McC


1 Answers

@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!

like image 195
Michael McC Avatar answered Feb 22 '26 01:02

Michael McC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!