简体   繁体   中英

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

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, eg 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM