Positional operators and dynamic index values

Hi there,

I am using the $set update operator with $[] positional operator to target a nested array item. In the following -

$set: {   
    'doctors.$[a].patients.$[b].medication.$[c].scriptNotes.1': scriptNotesDetail,
}

… can the index value ‘1’ (for field scriptNotes.1) be a dynamic variable? For example, if const indexValue = 3, can I somehow reference the variable indexValue in place of the hardcoded ‘1’? I would like to use an index value not a field value.

Hope that makes sense. Many thanks for your help.

This is standard javascript. Search for javascript dynamic key name in google.

2 Likes

Perfect! Didn’t even think to acknowledge I was simply working with a JS object. Below syntax worked.

$set: {   
    [`doctors.$[a].patients.$[b].medication.$[c].scriptNotes.${dynamicIndexVariable}`]: scriptNotesDetail,
}
2 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.