doubt
doubt

Reputation: 315

How to update using upsert in MongoDB using JPA

I want to add insert a record in MongoDB if the unique key combination doesn't exist else insert the record using JPA in springboot.

The code to insert is as follows. In the following id1 and id2 is a unique key.

@Autowired
MyEntityRepository  myEntityRepository;
.........
MyEntity entity = new MyEntity();
entity.setId1(id1);
entity.setId2(id2);
entity.setTime(time);
myEntityRepository.save(entity);

How to update the above using upsert?

Upvotes: 0

Views: 803

Answers (1)

Anand Mattikopp
Anand Mattikopp

Reputation: 372

myEntityRepository.save() already uses upsert. It will insert a new record if the key doesn't exists.

But I believe you want to save in MongoDB if it's new record and save in DB only if it exists. In that case, you need to explicitly check if the records exists for the given key.

Upvotes: 0

Related Questions