Java中使用MongoTemplate写聚合函数样例

mongo shell 语句

db.activity_service_log.aggregate([{
    $match: {
        "date": "2020-11-02",
		"result": "命中成功"
    }
},
{
    $group: {
        _id: {
            activityCode: "$activityCode",
            channel: "$channel"
        },
        activityCode: {
            "$first": "$activityCode"
        },
        channel: {
            "$first": "$channel"
        },
        total: {
        $sum: 1
        }
    }
}])

对应MongoTemplate语句

import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;

Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("date").is("2020-11-02").and("resut").is("命中成功")), 
Aggregation.group("activityCode", "channel").first("activityCode").as("activityCode").first("channel").as("channel").count().as("total"));

tip: 

shell语句里的 $group{total: {$sum: 1}} 
在java中需要用:
Aggregation.group().count().as("total")) 代替

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值