Karaja
Karaja

Reputation: 415

How do I dynamically set the field I wish to update in MongoDB

I need to update a specific element of a highly nested array object but I can't dynamically choose the field any thoughts? I basically need to run the following in a for loop.

collection.updateOne({ _id: "MY_ID"},[
  {
    $set: {
       `array1.${i}.array2.${j}.id_field` : new UUID()
    },
  },
])

Upvotes: 0

Views: 544

Answers (1)

Karaja
Karaja

Reputation: 415

Figured it out, all I have to do is wrap the string in brackets [].

collection.updateOne({ _id: "MY_ID"},[
  {
    $set: {
       [`array1.${i}.array2.${j}.id_field`] : new UUID()
    },
  },
])

Upvotes: 2

Related Questions