MongoDB和MongoTemplate模拟SQL的ifNull

近日需求中用到这个,但是网上找到的答案并不理想,在查阅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")),

你可能感兴趣的:(MongoDB和MongoTemplate模拟SQL的ifNull)