title: Update elements inside a array MongoDB using Java
body: <p><strong>A sample JSON Document</strong></p>
  
  <pre><code>{
  "_id" : "ab85cebc-8c7a-43bf-8efc-1151ccaa4f84",
  "address" : {
      "city" : "Bangalore",
      "postcode" : "560080",
      "countrycode":"in",
      "street" : "SADASHIVNAGAR,SANKEY TANK RD"
  },
  "brand" : "Shell",
  "prices" : [ 
      {
          "fuelType" : "DIESEL",
          "price" : 52.7
      }, 
      {
          "fuelType" : "PETROL",
          "price" : 67.05
      }
  ]
  }
  </code></pre>
  
  <ul>
  <li>I have around <code>20 docs</code> for <code>brand:Shell</code> with different location in and around Bangalore.</li>
  <li>For all those I have to update <code>Diesel</code> and <code>Petrol</code> price.</li>
  </ul>
  
  <p>Say current <code>DIESEL</code> and <code>PETROL</code> prices are <code>57.9</code> and <code>71.4</code> respectively?</p>
  
  <p>How do I update all document with these latest price using <code>JAVA (using Eclipse IDE)</code></p>
  
  <p><strong>Code (in complete)</strong></p>
  
  <pre><code>public class UpdateGasstationFuelPrice {
  
  public static void main(String[] args) {
      MongoClient client = new MongoClient("localhost",27017);
      MongoDatabase db = client.getDatabase( "notes" );
  
      MongoCursor&lt;Document&gt; cursor = db.getCollection( "gasstation" ).find( new BasicDBObject( "address.countrycode","in" )
          .append("address.city","Bangalore")
          .append("brand","Shell")).iterator();
  
      if (cursor.hasNext()){
          Document doc = cursor.next();
      }
      client.close();
  }
  }
  </code></pre>
  
  <p><strong>Update with Query</strong></p>
  
  <pre><code>  db.getCollection("gasstation").update({"address.countrycode":"in","address.city":"Bangalore","brand":"Shell"},   
              //Query to get the position
              { 
                "prices":  { $exists: true }  
              },
              // Use the positional $ operator to update specific element (which matches your query    
              { 
                $set: 
                    { 
                      //set value specific to elements field/key
                      "prices" : [
                          {
                              "fuelType" : "DIESEL",
                              "price" : 502.7
                          }, 
                          {
                              "fuelType" : "PETROL",
                              "price" : 607.05
                          }
                        ] 
                    } 
              } 
          );
  </code></pre>