This is the json object
{
"account_id":"1",
"sections":[ {
"section_name":"abc",
"labels": [{
"name": "label1",
"value": "value1"
},
{
"name": "label2",
"value": "value2"
}]
},
{
"section_name":"def",
"labels": [{
"name": "label3",
"value": "value3"
}]
}]
}
In this json object I wanted to change the value of label3 from value3 to value4 in the section def. There are different accounts but I have listed only one json object here.
I have used the below code, but it didn't work for me. Here I have passed section name(section), label name (label) and label value (value).
let query = {
account_id: event.accountId.toString(),
sections: {
section_name: section,
labels: {
label_name: label
}
}
};
return using(connectDatabase(), db => {
return db.collection(TABLE_NAME).updateOne(query, { $set: {
'sections.$.labels.$.value': value } });
}).then(
result => {
cb(null, responseObj(result, 200));
},
err => {
cb(responseObj(err, 500));
}
);
Can someone help me ? Thanks in advance
-
any errors while running that query?Naga Sai A– Naga Sai A2019年03月11日 03:47:40 +00:00Commented Mar 11, 2019 at 3:47
-
Its not updating in the database.Uthpala Pitawela– Uthpala Pitawela2019年03月11日 03:48:38 +00:00Commented Mar 11, 2019 at 3:48
-
posted answer using arrayFilters, hope it works for youNaga Sai A– Naga Sai A2019年03月11日 05:13:43 +00:00Commented Mar 11, 2019 at 5:13
2 Answers 2
To achieve expected result, use below option of using arrayFilters for nested objects
- Get main Object using account_id
- Using ArrayFiter
$[identfier].section : "def"and$[identfier].name: "label3"
db.collection(TABLE_NAME).updateOne({
account_id: event.accountId.toString(),
{
"$set": {
"sections.$[elem].labels.$[label].value": value
}
},
{
"arrayFilters": [{
"elem.section_name": section
}, {
"label.name": label
}]
}
})
Please refer this link for more details - https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
Another example of arrayFilters with example - How to Update Multiple Array Elements in mongodb
8 Comments
Updated Query You can use this query
db.testcol.update(
{ },
{ $set: { "sections.$[element].labels.$[element1].value" : "value1New" } },
{ multi: true,
arrayFilters: [ { "element.section_name": { $eq: "abc" } }, { "element1.name": { $eq: "label1" } }]
}
)
You can check the following query: Where 1 is the index value of the array.
db.testcol.update(
{
account_id:"1",
"sections.section_name":"def"
},
{
$set:{
"sections.1.labels.1.value":"value8"
}
}
)
If you want to update all the values then you can use:
db.testcol.update(
{
account_id:"1",
"sections.section_name":"def"
},
{
$set:{
"sections.$[].labels.$[].value":"value8"
}
}
)
Please check and let me know if it is help-full.