DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects
  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • A Comprehensive Guide To Working With JSON in JavaScript
  • How To Generate Scripts of Database Objects in SQL Server

Trending

  • Engineering Closed-Loop Graph-RAG Systems, Part 3: Closing the Loop in Graph-RAG Systems
  • Why Round-Robin Won't Save You: Load Balancing Challenges in Data Streaming Services With Heterogeneous Traffic
  • AI Paradigm Shift: Analytics Without SQL
  • Ingesting Fixed-Width Mainframe Files Into Delta Lake: The Details Nobody Writes Down
  1. DZone
  2. Coding
  3. Languages
  4. Update a Specific Value in a Multi-Level Nested JSON Document Using N1QL in Couchbase

Update a Specific Value in a Multi-Level Nested JSON Document Using N1QL in Couchbase

In this article, see how to update a specific value in a multi-level nested JSON document using N1QL in Couchbase.

By 
Himadri Subudhi user avatar
Himadri Subudhi
·
Apr. 17, 20 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
22.5K Views

Join the DZone community and get the full member experience.

Join For Free

In the example below, we will explore how to update an object in multi-level JSON data in Couchbase.

Recently, I’ve been working on Couchbase queries and got stuck while attempting to work with array of objects in highly nested json. Then I explored some Array features in Couchbase, which helped me to achieve the result I was looking for. We will go through same with example below.

Start With an Idea

Let’s consider you are running a university and you need data until the student level in all colleges is listed under the university. The document representing the sample data is below.

universityMaster:

JSON
 




xxxxxxxxxx
1
62


 
1
{
2

          
3
  "_class": "com.university.entity.universityDocument",
4

          
5
  "university": [
6

          
7
    {
8
      "collegeList": [
9
        {
10
          "collegeId": "1",
11
          "collegeName": "Common college",
12
          "collegeType": "Engineering",
13
          "branch": [
14
            {
15
               "studentList": [
16
                {
17
                  "studentId": "1",
18
                  "studentName": "Alice",
19
                   "studentSubjects": [],
20
                   "studentType": "TopTalent"
21
                },
22
                {
23
                  "studentId": "2",
24
                  "studentName": "Alex",
25
                  "studentSubjects": [],
26
                  "studentType": "Average"
27
                }
28
              ],
29
               "branchId": "1",
30
               "branchName": "Computer Science",
31
               "branchStrength": "60"
32
            },
33
            {
34
              "studentList": [
35
                {
36
                   "studentId": "3",
37
                   "studentName": "Mohit",
38
                   "studentSubjects": [],
39
                   "studentType": "TopTalent"
40
                },
41
                {
42
                   "studentId": "4",
43
                   "studentName": "Rajni",
44
                   "studentSubjects": [],
45
                   "studentType": "Average"
46
                }
47
              ],
48
               "branchId": "2",
49
               "branchName": "Electronics",
50
               "branchStrength": "60"
51
            }
52
          ]
53
        }
54
      ],
55
      "universityName": "BPUT",
56
      "universityId": "1",
57
      "universityType": "Technology",
58
      "universityGrade": "AAA"
59
    }
60
  ]
61
}
62

          



Requirement

You need to update student object inside studentList, which is nested under branch, which is under collegeList, which is under university.

Implementation

I need to update a single object that is at level 4 in a nested JSON document. So how can I get it Couchbase Array Functions is the solution.

First, I need to find out the array position of the element that needs to be updated. Let's understand what Array_Position is.

ARRAY_POSITION (expr,val) – This function returns the first position of the specified value within the array expression.

Below is the query:

SQL
 




xxxxxxxxxx
1
10


 
1
select array_pos(branch.studentList, studentList) from `university` 
2
as v unnest v.university as university
3
unnest university.collegeList as collegeList
4
unnest collegeList.branch as branch 
5
unnest branch.studentList as studentList
6
where university.universityId = "1" 
7
and collegeList.collegeId = "1" 
8
and branch.branchId = "1" 
9
and studentList.studentId = "1" 
10
and meta(v).id = "universityMaster" limit 1



Once the query is executed, it gives the below result:

JSON
 




xxxxxxxxxx
1


 
1
[
2
  {
3
    "$1": 0
4
  }
5
]



Now I need to update the required value on that position. The query for same is below. As you can see, I have passed the value I got from the above query, i.e “0” in branch.studentList[0]. We need to use Array_Flatten to achieve the same.

ARRAY_FLATTEN (expr,depth) – This function flattens the nested array elements into top level array, up to a specified depth.

SQL
 




xxxxxxxxxx
1
13


 
1
update `university` v use keys "universityMaster" set branch.studentList[0] = {
2
                   "studentId": "1",
3
                   "studentName": "Alice D",
4
                   "studentSubjects": [],
5
                   "studentType": "TopTalent"
6
                } 
7
FOR branch IN ARRAY_FLATTEN( ARRAY collegeList.branch 
8
FOR collegeList IN ARRAY_FLATTEN( ARRAY university.collegeList
9
FOR university WITHIN v.university WHEN university.universityId = "1" END, 1)
10
WHEN collegeList.collegeId = "1" END, 1)
11
WHEN branch.branchId = "1"
12
End returning *;



Results are below:

JSON
 




x
62


 
1
[
2
  {
3
    "v": {
4
      "_class": "com.university.entity.universityDocument",
5
      "university": [
6
        {
7
          "collegeList": [
8
            {
9
              "branch": [
10
                {
11
                  "branchId": "1",
12
                  "branchName": "Computer Science",
13
                  "branchStrength": "60",
14
                   "studentList": [
15
                    {
16
                       "studentId": "1",
17
                       "studentName": "Alice D",
18
                       "studentSubjects": [],
19
                       "studentType": "TopTalent"
20
                    },
21
                    {
22
                       "studentId": "2",
23
                       "studentName": "Alex",
24
                       "studentSubjects": [],
25
                       "studentType": "Average"
26
                    }
27
                  ]
28
                },
29
                {
30
                   "branchId": "2",
31
                   "branchName": "Electronics",
32
                   "branchStrength": "60",
33
                   "studentList": [
34
                    {
35
                       "studentId": "3",
36
                       "studentName": "Mohit",
37
                       "studentSubjects": [],
38
                       "studentType": "TopTalent"
39
                    },
40
                    {
41
                       "studentId": "4",
42
                       "studentName": "Rajni",
43
                       "studentSubjects": [],
44
                       "studentType": "Average"
45
                    }
46
                  ]
47
                }
48
              ],
49
               "collegeId": "1",
50
               "collegeName": "Common college",
51
               "collegeType": "Engineering"
52
            }
53
          ],
54
           "universityGrade": "AAA",
55
           "universityId": "1",
56
           "universityName": "BPUT",
57
           "universityType": "Technology"
58
        }
59
      ]
60
    }
61
  }
62
]



Finally, I got the solution.

When Should I Use Nested Objects?

Nested objects are the solution when I need data structures containing collections of inner objects that are tightly coupled with outer objects or describes the outer object. So I have designed the above-mentioned example data set, which clearly describes the logic, i.e inside university many colleges, inside colleges many branches, and in each branch, many students are tagged.

JSON Document Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Introduction to Couchbase for Oracle Developers and Experts: Part 2 - Database Objects
  • Document Generation API: How to Automate Personalized Document Creation at Scale
  • A Comprehensive Guide To Working With JSON in JavaScript
  • How To Generate Scripts of Database Objects in SQL Server

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook