spring-data-mongodb的简单使用方法看这个: http://www.mytju.com/classcode/news_readNews.asp?newsID=744
要实现sql语句里的 select ipcc,count(*) as total from xxx group by ipcc order by total desc;
用MongoTemplate写的话,大概是这样:
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.aggregation.Aggregation; import org.springframework.data.mongodb.core.aggregation.AggregationResults; import com.mongodb.BasicDBObject;
... public void xx(){ // 聚合条件,相当于拼一个groupBy的sql语句 Aggregation agg = Aggregation.newAggregation( Aggregation.match(Criteria.where("duration").lt(300)), // where条件 Aggregation.group("ipcc").count().as("total"), // group by Aggregation.project("total").and("ipcc").previousOperation(), // select字段,默认groupby的那个字段,在结果里字段名是_id,所以用and("ipcc").previousOperation()改为ipcc,挺奇怪的用法。 Aggregation.sort(Sort.Direction.DESC, "total")); // 排序
// 执行查询,并把结果转成bean,这里偷懒,用了BasicDBObject这个万能bean AggregationResults<BasicDBObject> result = mongoTemplate.aggregate(agg, AgentTicketLog.class, BasicDBObject.class); List<BasicDBObject> list = result.getMappedResults(); for (BasicDBObject dbo : list) { String key = dbo.getString("ipcc"); long total = dbo.getLong("total"); System.out.println(key + ":" + total); } }
更多用法,自己点点看就行了。 从日志里,可以看到执行的聚合json是:
{ "aggregate":"agentTicketLog", "pipeline":[ { "$match":{ "duration":{ "$lt":300 } } }, { "$group":{ "_id":"$ipcc", "total":{ "$sum":1 } } }, { "$project":{ "total":1, "_id":0, "ipcc":"$_id" } }, { "$sort":{ "total":-1 } } ] }
|