下面這一段就是用java代碼來實現mongodb的聚合函數aggrega.
Aggregation agg = Aggregation.newAggregation(
Aggregation.match(criteria),//條件
Aggregation.group("a","b","c","d","e").count().as("f"),//分組字段
Aggregation.sort(sort),//排序
Aggregation.skip(page.getFirstResult()),//過濾
Aggregation.limit(pageSize)//頁數
);
AggregationResults<Test> outputType=mongoTemplate.aggregate(agg,"test",Test.class);
List<Test> list=outputType.getMappedResults();
mongodb原語句:
db.getCollection('test').aggregate( [
{ $match : { score : { $gt : 70, $lte : 90 } } },
{ $group: { _id: null, count: { $sum: 1 } } },
{ $sort:a},
{ $skip:10},
{ $limit:10}
] );
類似於sql
select a,b,c,count(1) from test where ... group by (...)