Search code examples
javaarraysjsoncouchdbektorp

Removing an item from an array in CouchDB


what I am trying to do is updating a document, which has this pattern:

{
    "_id":"myObjectId",
    "_rev":"4-cf19d80a7315bb7fc72882839d7eccb9",
    "properties":
	{
	 "1b5f313d044f7cd4d46f62c96e8e26d68":"9f5afece4144ab5676375335150a9776",
         "2f127235e8302fb6fdcbec41f05a059cf":"2190e8ce6a07bd025ea150187a47e11af",
         "99927ee3855e87d44c05f1bc881a3726":"359f664a4e43d5dde05a7f7ff41551b7a",
         {And so on, that's not the point}
	}
	,
    "projects":[
	  { "_id":"project_0","name":"1704e5cafc16e18af2076dc7b640fc9cc" }
	  ,
	  { "_id":"project_1","name":"2a69038d0133688518aadf02affe746c3" }
	  ,
	  { "_id":"project_2","name":"228854981f9c5d37439b2736cb952444c" }
      , {And so on ...}
  ]
}

What I am trying to achieve is removing or adding one "project" from this document. I tried using the LightCouch Java API and Ektorp, but both do not provide ways to do so (which is understandable).

So far, the only way I found was fetching a document, getting it's content, removing manually the array and updating this document. And it is not working very well, to be honest. The problem is, as I get my document as a String, I have trouble inserting my changes into it (e.g removing a project) and updating it (the most troublesome part is updating to me).

So I have two questions: - Are there ways to doing it more simply ? - How can I remove/add an item from a Json array and updating my document ?

I am new to those technologies and am trying to work my way around, but I think I have problems understanding Serialization / Deserialization concepts while working with those Java APIs.

Thank you, in advance.


Solution

  • Having a quick look at the docs for LightCouch, it should be pretty easy for you to use JSON for ad hoc manipulation. If you already have Java objects that represent the document you would be better of using that, but you haven't mentioned it.

    To use JSON you could get the document like this:

    CouchDbClient dbClient = new CouchDbClient();
    JsonObject myDoc = dbClient.find(JsonObject.class, "myObjectId");
    

    That is a com.google.gson.JsonObject object. So you should be able to do this:

    JasonArray projects = myDoc.getAsJsonArray("projects");
    JsonObject newProject = new JsonObject();
    newProject.addProperty("_id", "project_10");
    newProject.addProperty("name", "92837402937408237492837");
    projects.add(newProject); //add a new entry
    project.remove(0); //remove the first entry
    

    And save it back:

    dbClient.save(myDoc);