SpringDataMongoDB是MongoDB必须的依赖,它其中有Query和Update等对象,也有mongoTemplate注入对象.
我们可以通过这些来实现有条件的更新某些字段,就如同sql中的语句’set number = 20 where age = 10’一样.
public class WebTest {
@Autowired
private MongoTemplate mongoTemplateObj;
@PostMapping("/matchSave")
public String matchSave(MatchsInfo matchsInfoObj) {
Query queryObj = new Query(Criteria.where("number").is(matchsInfoObj.getNumber()));//指定更新条件,number字段的值等于实体类的number值时进行更新.
Update updateObj = new Update().set("yeahAndMonthAndDay", matchsInfoObj.getYeahAndMonthAndDay())//指定要更新的字段和值
.set("quizNumber", matchsInfoObj.getQuizNumber())
.set("matchName", matchsInfoObj.getMatchName())
.set("homeName", matchsInfoObj.getHomeName())
.set("guestName", matchsInfoObj.getGuestName())
.set("startTime", matchsInfoObj.getStartTime())
.set("sOkMoney", matchsInfoObj.getsOkMoney())
.set("pOkMoney", matchsInfoObj.getpOkMoney())
.set("fOkMoney", matchsInfoObj.getfOkMoney())
.set("sScale", matchsInfoObj.getsScale())
.set("pScale", matchsInfoObj.getpScale())
.set("fScale", matchsInfoObj.getfScale())
.set("sOdds", matchsInfoObj.getsOdds())
.set("pOdds", matchsInfoObj.getpOdds())
.set("fOdds", matchsInfoObj.getfOdds())
.set("sIndex", matchsInfoObj.getsIndex())
.set("pIndex", matchsInfoObj.getpIndex())
.set("fIndex", matchsInfoObj.getfIndex());
// updateFirst() 更新符合条件的第一条数据. updateMulti() 更新符合条件的所有数据. upsert() 修改符合条件时如果不存在则添加.
UpdateResult updateFirst = mongoTemplateObj.updateFirst(queryObj, updateObj, MatchsInfo.class);
return null;
}
}
参考:
https://blog.csdn.net/yu757371316/article/details/73348932
https://blog.csdn.net/jiangshuanshuan/article/details/93175801
该博客介绍了如何利用SpringDataMongoDB的Query和Update对象,结合mongoTemplate,实现对MongoDB文档的有条件更新操作,类似于SQL的更新语句。通过创建查询条件和更新设置,可以更新匹配条件的第一个或所有数据。

5604

被折叠的 条评论
为什么被折叠?



