【问题标题】:How to update particular field in mongo db by using MongoRepository Interface?如何使用 MongoRepository 接口更新 mongo db 中的特定字段?
【发布时间】:2016-12-22 17:31:26
【问题描述】:

春季如何使用 MongoRepository 接口更新 mongo db 集合中的特定字段?

【问题讨论】:

  • 除了 MongoRepository 你还知道其他存储库吗?
  • 简短的回答是否定的
  • 你得到解决方案了吗?

标签: java spring spring-mongodb mongorepository


【解决方案1】:

从今天开始,您无法通过一个查询使用MongoRepository 更新文档。如果您真的想使用MongoRepository 更新特定字段,那么以下是步骤:

  1. 获取要更新的文档
  2. 为特定字段设置新值并保存该文档。

例子:

MyDocument myDocumentToUpdate = myDocumentRepository.findById(documentId); // fetching a document that you want to update the field
myDocumentToUpdate.setMyField(myNewValue); // setting the new value to the field myField
myDocumentRepository.save(myDocumentToUpdate); // saving (It basically updates the document) the updated document

【讨论】:

  • 这似乎具有覆盖整个文档的效果,而不仅仅是更新单个字段的值。
  • 是的。在内部,它不会更改特定字段,但作为用户,它似乎会这样做。
【解决方案2】:

我相信你现在已经得到了答案,还在更新它以帮助其他人。

您可以通过以下代码更新特定字段。,

 Query query1 = new Query(Criteria.where("id").is("123"));
              Update update1 = new Update();
              update1.set("available", false);
              mongoTemplate.updateFirst(query1, update1, Customer.class);

【讨论】:

  • 这个方法使用的是MongoOperation,而不是MongoRepository
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多