mongodbmongorepository

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.


Solution

  • 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
    }