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?