简体   繁体   中英

How can I store and update the nested json object into couchbase using java sdk

I am using couchbase Community Edition 5.0.1 and java-client 2.7.4. I want to store the following nested json object into couchbase. If I want to update the same object without affecting the other fields.

Eg:

  1. If I want to add one more player object under players object array
  2. If I want to add One more group say 'Z Group' under group object array

How can I Achieve this without affecting other fields.

 {
    "doctype": "config:sample",
    "group": [{
            "name": "X Group",
            "id": 1,
            "players": [{
                    "name": "Roger Federer",
                    "number": 3286,
                    "keyword": "tennies"
                },
                {
                    "name": "P. V. Sindhu",
                    "number": 4723,
                    "keyword": "badminton"
                }
            ]
        },
        {
            "name": "Y Group",
            "id": "2",
            "players": [{
                    "name": "Jimmy Connors",
                    "number": 5623,
                    "keyword": "tennies"
                },
                {
                    "name": "Sachin",
                    "number": 8756,
                    "keyword": "Cricket"
                }
            ]
        }
    ]
}

N1QL has a huge variety of functions to operate on arrays:

https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/arrayfun.html

In your case, you could simply use ARRAY_INSERT or ARRAY_PREPEND

Check out update/update-for syntax (last example) https://docs.couchbase.com/server/current/n1ql/n1ql-language-reference/update.html

UPDATE default AS d
SET d.group = ARRAY_APPEND(d.group, {......})
WHERE .....;

UPDATE default AS d
SET g.players = ARRAY_APPEND(g.players, {......}) FOR g IN d.group WHEN g.id = 2 END
WHERE .....;

If you know which document IDs you want to update you can use the key-value subdocument API, which will generally be faster than going via N1QL for a single document update.

This will add a new player to the end of X Group's "players" array:

bucket.mutateIn(docId)
        .arrayAppend("group[0].players",
                JsonObject.create()
                        .put("name", "John Smith"))
                        // ... other player JSON
        .execute();

And this will add a new Group Z to the "group" array:

bucket.mutateIn(docId)
        .arrayAppend("group",
                JsonObject.create()
                        .put("name", "Z Group"))
                        // ... other group JSON
        .execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM