简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM