0

In Spring Boot I want to update a field in collection using other field from that collection.
I tried this, but it doesn't work.

public void setTypeOfPayment(MongoTemplate mongoTemplate) {
    Query query = new Query();
    Criteria paymentTypeFilter1 = Criteria.where("payment_type").is("SOME1");
    Criteria paymentTypeFilter2 = Criteria.where("payment_type").is("SOME2");
    query.addCriteria(paymentTypeFilter1.orOperator(paymentTypeFilter2));
    Update update = new Update();
    update.set("payment.type_of_payment", "$payment_type");
    mongoTemplate.updateMulti(query, update, Report.class);
  }

I want to put existing payment_type value into payment.type_of_payment but I only get string $payment_type.
Is there a way to achieve this?

Update: my MongoDb version is 4.0.6.

1 Answer 1

2

If you have the recent versions of spring data MongoDB, you can try using AggregationUpdate like this:

public void setTypeOfPayment(MongoTemplate mongoTemplate) {
    Query query = new Query();
    Criteria paymentTypeFilter1 = Criteria.where("payment_type").is("SOME1");
    Criteria paymentTypeFilter2 = Criteria.where("payment_type").is("SOME2");
    query.addCriteria(paymentTypeFilter1.orOperator(paymentTypeFilter2));
    AggregationUpdate update = AggregationUpdate.update().set("payment.type_of_payment")
                .toValueOf("payment_type")
    mongoTemplate.updateMulti(query, update, Report.class);
}
Sign up to request clarification or add additional context in comments.

4 Comments

I experienced this error: stackoverflow.com/questions/56814957/…. It is because my MongoDb version is 4.0.6. However, thanks for answer. It will serve me to convince my admin to update MongoDb version.
In the current version, you can do it, by fetching all the documents, looping over and updating them in java, and then using saveAll method of repository
You can do that in each version, but that is not good way of doing bulk updates.
Yeah, not the best way, but the worst-case scenario.

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.