Reputation: 193
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
}
]
}
20 docs
for brand:Shell
with different location in and around Bangalore.Diesel
and Petrol
price.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
}
]
}
}
);
Upvotes: 2
Views: 5182
Reputation: 21629
You cannot updated util you know the position of the element which you want to update.
So basically what you can do is:
db.gasstation.update( //Query to get the position { "prices.fuelType": "DIESEL" }, // Use the positional $ operator to update specific element (which matches your query { $set: { "prices.$" : //Element/new value to update { "fuelType" : "DIESEL", "price" : 999.7 } } } );
If you want just to update only specific field inside the json element embedded in the array you can do as follows:
db.gasstation.update( //Query to get the position { "prices.fuelType": "DIESEL" }, // Use the positional $ operator to update specific element (which matches your query { $set: { //set value specific to elements field/key //i.e. Update documents in an Array "prices.$.price" : 999.7 } } );
db.gasstation.update( //Query to match { "address.city":"Bangalore", "brand":"Shell", "countrycode":"in", "prices": { $exists: true } }, // Use $set operator & overwrite entire array { $set: { //Overwrite value "prices" : [ { "fuelType" : "DIESEL", "price" : 502.7 }, { "fuelType" : "PETROL", "price" : 607.05 } ] } } );
Upvotes: 1