Update nested object by key

The idea would be this I think. Feel free to replace updateOne, I just tested without any driver.

(The computed property name must point to an array)

const stringExample = "Are you a veggie?"
db.sales.updateOne(
          { _id: exampleID },
          {
            $push: {
              [`extraFields.topic1.${stringExample}.email`]: "example value",
            },
          }
        )

I think keys with spaces are not a good idea normally, but that is your choice. For example, you may camelcase it using some library.

2 Likes