0

Based on my previous question Springboot MongoDB delete an object from array of objects I'm able to remove an object from an array of objects in mongodb collection. Below code is working for me to remove:

String pin = httpServletRequest.getParameter("address_pin")
                        .trim();                           
Query query = new Query();
query.addCriteria(Criteria.where("customer_id")
                .is(customerId)
                .and("customer_addresses.address_india")
                .elemMatch(Criteria.where("address_pin").is(pin)));
                            
Update update = new Update();
update.pull("customer_addresses.address_india", Collections.singletonMap("address_pin", pin));
                            
UpdateResult result = mongoTemplate.updateMulti(query, update, "customer_addresses");
System.out.println("::: DELETE SUCCESS ::: " + result.wasAcknowledged());
                            
    //  FindAndModifyOptions options = FindAndModifyOptions.options();
    //  options.returnNew(true);
    //  CustomerAddress addressesAfterDelete =  mongoTemplate.findAndModify(query, update, options, CustomerAddress.class);
    //  System.out.println("::: AFTER DELETE ::: " + addressesAfterDelete.getCustomerAddresses().toString());

Here, updateMulti and findAndModify both are working fine. I can verify in Compass that the object matching with the criteria has been removed.

Is there any built-in method in UpdateResult or in FindAndModifyOptions to verify? result.wasAcknowledged() returns true even if query criteria does not meet.

How do I verify delete in mongodb was successful or not in spring-boot?

2
  • If it was not successful there would've been an error/exception thrown. Commented Feb 3, 2022 at 20:04
  • findAndModify - return data can show the updated document. Commented Feb 4, 2022 at 5:49

0

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.