0

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.

1 Answer 1

1

You could easily do this with a simple updateMany command.

db.collection.updateMany(
   { "temp_F": { "$exists": false } },
   [
      {
         "$set": {
            "temp_F": {
               "$add": [
                  { "$multiply": [ 1.8, "$temp" ] },
                  32
               ]
            }
         }
      }
   ]
)

With the Java API, the MongoDB command would transform in the following code:

Bson filter = Filters.eq("temp_F", null);
Bson update = Updates.combine(
    Updates.set("temp_F", 
        new Document("$add", Arrays.asList(
            new Document("$multiply", Arrays.asList(1.8, "$temp")),
            32
        ))
    )
);
UpdateResult result = collection.updateMany(filter, update);
Sign up to request clarification or add additional context in comments.

3 Comments

Can u please add import statement for Document ?
You need to import it via the org.bson.Document package.
I have a similar problem: is there no way to let it work with spring boot lib?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.