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: :)
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"}],
}
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.