Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update few fields in mongodb by using MongoRepository?

I have a User POJO having fields:

@Id
    private String _id;
    private String phone;
    private String email;
    private String password;
    private String userName;
    private String dob;
    private String gender;
    private String city;
    private String pincode;
    private String status;
    private String validUpto;
    private List<String> userRole;
    private String persona;

I saved all the fields in MongoDB (document). Now I want to update only few fields like city, Pincode.

I also refer this question, but it is not giving the answer via MongoRepository.

is there any way we can update only few fields via MongoRepository instead of MongoTemplate.

like image 354
Payal Avatar asked Dec 02 '25 23:12

Payal


1 Answers

The repository doesn't provide an 'update' operation only .save(object);

But you can update it by retrieving the Object from the repository, change the relevant fields. Afterwards, you save the updated object to the repository.

Which will get you the desired result of 'updating'.

Spring-boot/SpringRepository example.

@Autowired
UserRepository userRepository;

@Test
public void testUpdateUser() throws Exception {
    User foundUser = userRepository.findById("1");  

    foundUser.setCity("Helsinki");
    // foundUser.setOtherFields("new values");
    userRepository.save(foundUser); // Will 'update' but it essentially replaces the entity in database
}
like image 92
Tony Avatar answered Dec 08 '25 07:12

Tony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!