How to update values in array using n1q1

27 views Asked by At

My couchbase bucket document looks like below

{
"Records": 
 [
    {
      "record_id": "21",
      "amount": 10,
      "count": 2
    },
    {
      "record_id": "22",
      "amount": 30,
      "count": 3
    }
 ],
"overall_amount": 40,
"overall_count": 5
}

I want to write a n1q1 update query which will update the count value inside Records array. If I update 1st object count from 2 to 5, then I want the overall_count value to get updated to 8.

Expected document should look like below when count increased from 2 to 5

{
"Records": 
[
   {
     "record_id": "21",
     "amount": 10,
     "count": 5
   },
   {
     "record_id": "22",
     "amount": 30,
     "count": 3
   }
],
"overall_amount": 40,
"overall_count": 8
}

How to achieve this?

1

There are 1 answers

0
vsr On
UPDATE default AS d 
SET a.`count` = a.`count` + 3  FOR a IN d.Records WHEN a.record_id = "21" END,
    d.overall_count = d.overall_count + ARRAY_SUM(ARRAY 1 FOR v IN d.Records WHEN v.record_id = "21" END) * 3 
WHERE ......;

OR

UPDATE default AS d 
SET d.Records[0].`count` = 5 ,
    d.overall_count = 8
WHERE ......;