我想知道有没有什么方法可以直接在后台更新mongodb文档,并将更新后的数据发送到前端,就像我们过去更新MySQL转储文件并将数据发送到前端一样。
发布于 2019-04-15 21:27:38
您可以使用findAndUpdate方法,通过mongoTemplate更新记录并在中返回。有关详细信息,请查看官方文档10.5.6. Finding and Upserting Documents in a Collection。要快速解决此问题,请查看以下代码:
// find and update and then return
Query query = new Query();
query.addCriteria(Criteria.where("firstName").is("First Name"));
Update update = new Update();
update.set("lastName", "modified last name");
FindAndModifyOptions options = new FindAndModifyOptions();
options.upsert(true);
options.returnNew(true);
try {
Customer modifiedCustomer = mongoOperation
.findAndModify(query, update, options, Customer.class);
// Modified data
System.out.println("Modified Custom data\n");
System.out.println(modifiedCustomer);
// Return from here;
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}我已经在我的github存储库中提交了这些代码,您可以查看它:https://github.com/krishnaiitd/learningJava/blob/master/spring-boot-sample-data-mongodb/src/main/java/sample/data/mongo/main/Application.java
https://stackoverflow.com/questions/55684757
复制相似问题