spring data mongoDB 复杂聚合条件查询--使用$cond,SpEL表达式

关键


image.png

表的数据结构为:

{
    "_id": ObjectId("60a622c6c9c4186347340f2d"),
    "dateStr": "2021-05-13",
    "productId": NumberLong("11565"),
    "cn": "index_g",
    "articleNumber": "78734307626683",
    "productName": "xxxxxxxxx",
    "img": "images",
    "pagePv": NumberLong("209"),
    "pageUv": NumberLong("75"),
    "pageClickPv": NumberLong("21"),
    "pageClickUv": NumberLong("20"),
    "orderNum": NumberLong("8"),
    "orderCash": 0.11,
    "orderCost": 0,
    "orderGp": 0.11,
    "exposureCost": 0,
    "clickCost": 0.01
}

聚合的条件为:
分组聚合后需要计算clickCost

AggregationOptions aggregationOptions = AggregationOptions.builder().allowDiskUse(true).build();

        AggregationSpELExpression spELExpression = AggregationSpELExpression.expressionOf("cond(pageClickPv > 0, orderGp / pageClickPv, 0)");

        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("dateStr", groupItem)
                        .addToSet(groupOtherItem).as(groupOtherItem)
                        .addToSet("articleNumber").as("articleNumber")
                        .addToSet("productName").as("productName")
                        .addToSet("img").as("img")
                        .sum("pagePv").as("pagePv")
                        .sum("pageUv").as("pageUv")
                        .sum("pageClickPv").as("pageClickPv")
                        .sum("pageClickUv").as("pageClickUv")
                        .sum("orderNum").as("orderNum")
                        .sum("orderCash").as("orderCash")
                        .sum("orderCost").as("orderCost")
                        .sum("orderGp").as("orderGp"),
                Aggregation.project("dateStr", groupItem, groupOtherItem, "articleNumber", "productName", "img", "pagePv"
                        , "pageUv", "pageClickPv", "pageClickUv", "orderNum", "orderCash", "orderCost", "orderGp")
                        .andExpression("orderGp / pagePv").as("exposureCost")
                        .and(spELExpression).as("clickCost"),
                Aggregation.sort(Sort.by(getOrderBy(param))),
                Aggregation.skip((pageNum - 1) * pageSize),
                Aggregation.limit(pageSize)
        ).withOptions(aggregationOptions);

你可能感兴趣的:(spring data mongoDB 复杂聚合条件查询--使用$cond,SpEL表达式)