0

I'm new in MongoDB an I'm using mongoose with nodejs. Currently I'm trying to update a nested Array which looks like this:

array1: [
{
    name: "one"
    array2: [
        {
            value1: "test",
            value2: "test2"
        }
    ]
}
]

So now I want to update the value1 in array2. How can I achieve this? I'm using the atomic operator two times in my code like this but it doens't work:

const data = await DB.findOneAndUpdate(
    {
        "array1.name": "one",
        "array1.array2.value1": "test"
    },
    {
        "$set": {
            "array1.$.array2.$.value1": "test changed"
        },
    }
);

Any ideas how I can do this? Thanks! :)

Funkberater
  • 775
  • 8
  • 16
  • Does this answer your question: https://stackoverflow.com/questions/50645179/mongo-error-when-updating-cannot-use-the-part-to-traverse-the-element/50645494#50645494 ? – mickl Jun 19 '20 at 16:48
  • Does this answer your question? [arrayFilters in mongodb](https://stackoverflow.com/questions/51324876/arrayfilters-in-mongodb) – whoami - fakeFaceTrueSoul Jun 19 '20 at 17:29

1 Answers1

1

You can use arrayFilters to update the nested array.

  const data = await DB.findOneAndUpdate(
    {},
    {
      $set: {
        "array1.$[elem1].array2.$[elem2].value1": "test changed",
      },
    },
    {
      arrayFilters: [{ "elem1.name": "one"}, {"elem2.value1": "test"}],
    }
  );
vishnu
  • 1,961
  • 2
  • 7
  • 11