欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-05-04 16:54:55
...

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")) 代替