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