使用 Spring Data MongoRepository 进行更新查询的自定义方法

我正在使用 org.springframework.data.mongodb.repository.MongoRepository.我写了一些自定义方法,如下所示,

I am using org.springframework.data.mongodb.repository.MongoRepository. I have written some custom method like below,

public interface DocRepository extends MongoRepository<Doc, String> {
     Doc findByDocIdAndAssignmentId(final String docId, final String assignemtId);
}

如何编写一个自定义方法,在满足条件时更新所有条目.

How can I write a custom method which update all entries when meeting a criteria.

例如,如果分配 id 为xyz",则将文档倾斜字段设置为abc"?

For example set document tilte field to "abc" if assignment id is "xyz"?

推荐答案

1) 您需要创建接口,例如 CustomDocRepository 并将此接口添加为您的 DocRepository 的 Base:

1) You need to create inteface e.g CustomDocRepository and add this interfaces as Base for your DocRepository:

public interface DocRepository extends MongoRepository<Doc, String>, CustomDocRepository {

    void updateDocumentTitle(String id, String title);

}

2) 您需要为 DocRepository 添加实现:

2) You need to add implementation for the DocRepository:

@Repository
public class CustomDocRepositoryImpl implements DocRepository {
  @Autowired
  private MongoTemplate mongoTemplate;


@Override
public void updateDocumentTitle(String id, String title) {
    Query query = new Query().addCriteria(where("_id").is(id));

    Update update = new Update();
    update.set("title", title);
    mongoTemplate.update(Doc.class).matching(query).apply(update).first();
}
}

这就是你需要做的一切

相关文章