mongodb $ifNull 根据字段是否为null project新字段 spring实现

介绍语法 ifNull

Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.

官方例子

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

description字段为project新生成的 如果description字段不为null则使用该字段如果为null则填充Unspecified字符串
输出

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

java spring 实现该聚合代码

//选取top30 的统计
        Aggregation aggregation = Aggregation.newAggregation(
        //保留 money way  personUserId字段默认使用字段a如果为null使用字段b
                Aggregation.project("money","way").and(ConditionalOperators.ifNull("$a").then("$b")).as("personUserId"),
                Aggregation.match(Criteria.where("way").in(1,2)),
                Aggregation.group("personUserId").sum("money").as("sumIncome"),
                Aggregation.sort(Sort.Direction.DESC, "sumIncome"),
                Aggregation.limit(30)
        );
        List<Document> mappedResults = mongoTemplate.aggregate(aggregation, xxx.class, Document.class).getMappedResults();
        System.out.println(mappedResults);

记录一个spring使用数组表达式的方法

详细见" java – Spring Data – MongoDb聚合 ifNull" 参考链接

1.ArrayOperators.Size.lengthOfArray(
还可以使用类似
2…and((AggregationExpression) ArrayOperators.arrayOf(ConditionalOperators.ifNull(“ d i s t r i U s e r I d " ) . t h e n ( " distriUserId").then(" distriUserId").then("userId”)))这种进行操作不过这个语句是错误的只是提供思路

···
db.collection.aggregate([
{KaTeX parse error: Expected 'EOF', got '}' at position 27: …ame : "name" } }̲, {project: {
name: 1,
sent: {
KaTeX parse error: Expected '}', got 'EOF' at end of input: … "ifNull": [ “$audience”, [] ]
}
}
}
}]);
如何使用Spring数据进行上述mongo聚合?
Aggregation aggregation = Aggregation.newAggregation(
.match(Criteria.where(“name”).is(“name”))
.project(“name”) .and(ArrayOperators.Size.lengthOfArray(ConditionalOperators.ifNull(“audience”).then(Collections.emptyList()))).as(“sent”)
);
···

参考链接

cond官方文档
project官方文档
Conditional 操作符
ifNull语法
java – Spring Data – MongoDb聚合$ifNull

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值