A sample JSON Document
{
"_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
}
]
}
- I have around
20 docsforbrand:Shellwith different location in and around Bangalore. - For all those I have to update
DieselandPetrolprice.
Say current DIESEL and PETROL prices are 57.9 and 71.4 respectively?
How do I update all document with these latest price using JAVA (using Eclipse IDE)
Code (in complete)
public class UpdateGasstationFuelPrice {
public static void main(String[] args) {
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase( "notes" );
MongoCursor<Document> 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();
}
}
Update with Query
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
}
]
}
}
);
MongoCursor<Document> cursor = db.getCollection( "gasstation" ).find( new BasicDBObject("address.city","Bangalore") .append("brand","Shell")).iterator();