0

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?

James Z
12.3k10 gold badges27 silver badges50 bronze badges
asked Nov 29, 2023 at 18:26

1 Answer 1

1
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 ......;
answered Nov 30, 2023 at 13:14
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.