MongoDB和MongoTemplate模拟SQL的ifNull

本文介绍如何在MongoDB中模拟SQL的ifNull功能。通过原生MongoDB查询语句和MongoTemplate的使用,展示在查询时如何将description字段的null值替换为默认值,详细解释了查询步骤和代码实现。

近日需求中用到这个,但是网上找到的答案并不理想,在查阅MongoDB官网后,得到解决方案:

MongoDB

原生写法

等待查询数据,需要将description为null的数据在查询时候给默认值

{ "_id" : 1, "item" : "abc1", description: "product 1", qty: 300 }
{ "_id" : 2, "item" : "abc2", description: null, qty: 200 }
{ "_id" : 3, "item" : "xyz1", qty: 250 }

查询语句

db.inventory.aggregate(
   [
      {
         $project: {
            item: 1,
            description: { $ifNull: [ "$description", "Unspecified" ] }
         }
      }
   ]
)

结果

{ "_id" : 1, "item" : "abc1", "description" : "product 1" }
{ "_id" : 2, "item" : "abc2", "description" : "Unspecified" }
{ "_id" : 3, "item" : "xyz1", "description" : "Unspecified" }
MongoTemplate

写法:
在聚合中使用,先处理match条件,然后再project投影的时候对null值置默认值

Aggregation.project("description").and("description")
         .applyCondition(ConditionalOperators.IfNull.ifNull("description").then("Unspecified")),
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值