title: updating a value in an array in mongodb from java
body: <p>I have couple of documens in mongodb as follow:</p>
  
  <pre><code>{
  "_id" : ObjectId("54901212f315dce7077204af"),
  "Date" : ISODate("2014-10-20T04:00:00.000Z"),
  "Type" : "Twitter",
  "Entities" : [ 
      {
          "ID" : 4,
          "Name" : "test1",
          "Sentiment" : {
              "Value" : 20,
              "Neutral" : 1
          }
      },
      {
          "ID" : 5,
          "Name" : "test5",
          "Sentiment" : {
              "Value" : 10,
              "Neutral" : 1
          }
      }
  ]
  </code></pre>
  
  <p>}</p>
  
  <p>Now I want to update the document that has Entities.ID=4 by adding (Sentiment.Value+4)/2 for example in the above example after update we have 12.</p>
  
  <p>I wrote the following code but I am stuck in the if statement as you can see:</p>
  
  <pre><code> DBCollection collectionG;
     collectionG = db.getCollection("GraphDataCollection");
      int entityID = 4;
      String entityName = "test";
      BasicDBObject queryingObject = new BasicDBObject();
      queryingObject.put("Entities.ID", entityID);
      DBCursor cursor = collectionG.find(queryingObject);
  
      if (cursor.hasNext())
      {
          BasicDBObject existingDocument = new BasicDBObject("Entities.ID", entityID);
          //not sure how to update the sentiment.value for entityid=4
      }
  </code></pre>
  
  <p>First I thought I should unwind the Entities array first to get the value of sentiment but if I do that then how can I wind them again and update the document with the same format as it has now but with the new sentiment value ?</p>
  
  <p>also I found the this link as well :
  <a href="https://stackoverflow.com/questions/10522347/mongodb-update-an-object-in-nested-array">MongoDB - Update objects in a document&#39;s array (nested updating)</a></p>
  
  <p>but I could not understand it since it is not written in java query,
  can anyone explain how I can do this in java?</p>