I have a list of records. Each record needs to have 2 fields: temp(temperature in Celcius) and temp_F(temperature in Fahrenheit). temp field is available in mostly all records. But temp_F is missing in most of the records. I want to populate missing temp_F value in the record using the temp value of the record. Here is what i am doing:
Query updateTempFQuery = Query.query(Criteria.where("temp_F").isNull());
List<TelemetryReport>reports = mongoTemplate.find(updateTempFQuery,TelemetryReport.class);
for(TelemetryReport report:reports){
if(report.getTemp() == null) continue;
Double fahrenHeitValue = new BigDecimal("32").add(new BigDecimal("1.8").multiply(new BigDecimal(report.getTemp().toString()))).doubleValue();
// temperature in fahrenheit = 32 + 1.8*(temp in celcius)
Update applyUpdate = new Update().set("temp_F",fahrenHeitValue);
mongoTemplate.updateFirst(updateTempFQuery,applyUpdate,TelemetryReport.class);
}
But the code is throwing timeout error because of huge number of records. I want to do it using updateMulti and aggregation or some other similar methods. But i am unable to find some solution. Please help.
To optimize your operation for updating a large number of records in MongoDB, you can use the
updateMultimethod combined with an aggregation pipeline. This approach will allow you to perform the update in a more efficient manner, especially when dealing with a huge number of records.Here's how you can modify your code to use
updateMulti:temp_Fisnull.temp_Fdirectly in the update command.Here's a sample code snippet:
In this code:
updateis created with an aggregation pipeline. The$condoperator is used to check iftempis not null. Iftempis not null, it calculates the Fahrenheit value. Otherwise, it keeps the originaltemp_F.updateMultimethod is used to apply this update to all documents matching the query.This approach should be significantly faster than iterating over each document and updating them one by one, especially for a large dataset.
Ensure that your MongoDB server is version 4.2 or later, as this feature is not available in earlier versions.