0
votes

I use Java Spring Boot and MongoDB repository in my project. I need to save and update documents in MongoDB.

The document can be saved or updated in MongoDB by save() method in the CrudRepository interface. As I understand from documentation MongoDB mechanism looking for the document with the same id and update it in case if a document with the same id was found or save in case if it was no found.

In my case, I need to customize this behaviour and save or update new documents not according to the id field but according to the email field. In case of a document with the same email exists it should be updated, in case if it does not exist it should be saved as a new document.

Here is the example of the document:

@Document("User")
@Data
public class User {
    @Id
    private String id = "abc123";
    private String email = "[email protected]";
    private String password = "some_hashed_password";
    private String name John Johnson;
}

Here how I try to save/update it:

User user = userRepository.save(user);

So I expect that in case if in Users collection exists a user with email "[email protected]" the document will be updated, in case if Users collection document with the email "[email protected]" not exists it will create one.

Is it possible to customize the save/update behavior according my needs so it will update or save documents according to email field, and how it can be implemented?

1

1 Answers

1
votes

You have to look it up, first:

User user = userRepository.findByEmail("[email protected]")

And then update the user that it found. When you subsequently save the user, it will update that user.

If you use MongoTemplate, it has more methods that might fit your use case, although using repositories make things a lot simpler, and you don't have to worry about the boilerplate code. You can look at https://www.baeldung.com/spring-data-mongodb-tutorial for more information.