{{announcement.body}}
{{announcement.title}}

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

DZone 's Guide to

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.

· Database Zone ·
Free Resource

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
 







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
 







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

JSON
 







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
 







Results are below:

JSON
 







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.

Topics:
couchbase 6.5 ,couchbase collections ,couchbase n1ql ,couchbase tutorial ,database ,json ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}