Alex
Alex

Reputation: 7521

How to update a SpringData MongoDB document inside a loop?

I have the POJO mapped to SpringData MongoDB Document

@Document(collection = “cacheVersion” ) 
public class CacheVersionBean {
    private boolean active = true;
    ...

Then I find the list in the MongoDB and try modification of the MongoDb document inside the list using MongoTemplate save:

Query query = new Query().addCriteria(Criteria.where("active").is(true));
List<CacheVersionBean> versionBeans = mongoTemplate.find(query, CacheVersionBean.class);
for (CacheVersionBean cacheVersionBean: versionList)
{
    cacheVersionBean.setActive(false);
    mongoTemplate.save(cacheVersionBean);
    ...

However, instead of modifying the document in the database this code creates the new Document. What is the easiest way for updating?

Upvotes: 1

Views: 314

Answers (1)

robjwilkins
robjwilkins

Reputation: 5672

I think you need to add an @Id annotated field (String or BigInteger) to your POJO (or simply a field named 'id' of those types). Spring will use this and then understand that the document you are saving is already in the database, and update it rather than creating a new document:

http://docs.spring.io/spring-data/data-document/docs/current/reference/html/#d0e1508

Upvotes: 1

Related Questions