Append/Prepend to a nested attribute

The Couchbase Developer’s Guide states:

Similarly, if you have JSON document with nested attributes, when you prepend and append, the new data will appear either before or after the entire JSON object, but not within the JSON object, nor any nested attributes in the JSON.

In light of this, what is the best way to append a value to a nested array, assuming for example we want to append the following:

{ "response": "200", "datetime": "2013-10-21 08:10:04" }

which needs to be added to the following Document inside the existing “responses” array:

{ "name": "My Website", "responses": [ { "response": "200", "datetime": "2013-10-21 08:05:36" }, { "response": "503", "datetime": "2013-10-21 08:02:18" } ] }

Bearing in mind that this Document may have up to around 10,000 “responses”, therefore a method of appending to the Document in-situ rather than retrieving it, manually injecting, and .setting the Document again would be preferable.

I’m currently doing the following:

new_result = { "response": response, "datetime":"%Y-%m-%d %H:%M:%S") } the_result = cb.get(the_key).value the_result["responses"].append(new_result) cb.set(the_key,the_result)



You are doing the correct thing, by extracting the document, parsing it and add the new JSON attribute to the JSON attribute itself.

About the size of the JSON document/attribute, since you have to download/upload the full document you have to be careful about the network and memory overhead. Maybe you can create sub documents. Also remember that Couchbase as a size limit for the value/document of 20Mb.

As you have mentioned, and it worth reminds it again, it is not possible to use the Couchbase append operation cb.append() / cb.prepend() , because these operations are appendin/prepending the whole string and not the JSON.