介绍语法 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