2

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

2 Answers2

1

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

juco
  • 6,331
  • 3
  • 25
  • 42
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
0

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.

Swati
  • 83
  • 1
  • 14
  • This does not work as sections.1.labels.1.value":"value8 , updates index 1 and sometimes the intended label not always in the index 0. – Uthpala Pitawela Mar 11 '19 at 05:10