MongoDB updating an array element in a specific index using the Java driver -


usually, avoid asking new question find "close-enough" answer problem.

but time surprisingly have fundamental , straightforward question - without lead.

i have straightforward mongodb document holds 2 arrays:

  • the 1st containing 3 numbers (ints) - each represent code-number of selected (predefined) question.

  • the 2nd holding 3 strings - answers given user these 3 correspondent questions.

for example, let's subject code 12 - "what's 1st dog's name?", , user's answer was: "spiky", etc...

so end like:

    {         "_id" : objectid("..."),         "questioncodesarray" : [                 12,                 56,                 3             ],         "answersarray" : [                 "spiky",                 "go swimming",                 "blabla.."             ]     } 

now, i'd able allow users change mind , choose different question , supply different answer it.

for this, need have index of element , access via index change using update() or findandmodify() [or other method] , answers out there "key-value style" not needed.

in simple java would've done like:

questionscodesarry[index] = newvalue; , answersarray[index] = newanswerstring;

all attempts write descent query simple index-based updating have failed.

any appreciated.

thank you.

in plain mongodb syntax need this:

collection.update({     /*your filter goes here*/ }, {     $set: {         "questioncodesarray.<zero-based-index>": "new value"     } }) 

i don't have java environment here translate driver's world. might able tonight, though.

still, vote different, more natural , less error-prone design you'd structure data so:

{     "_id" : objectid("59b635ffad44fad6662d8591"),     "answers" : [          {             "questioncode" : 12,             "answer" : "spiky"         },          {             "questioncode" : 56,             "answer" : "go swimming"         },          {             "questioncode" : 3,             "answer" : "blabla.."         }     ] } 

if that's option shall happily provide right update statement layout, too.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -