Spring Data MongoDB根据条件更新某字段.

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值