有数据如下
{ "_id" : 1, "domainName" : "test1.com", "hosting" : "hostgator.com" } { "_id" : 2, "domainName" : "test2.com", "hosting" : "aws.amazon.com"} { "_id" : 3, "domainName" : "test3.com", "hosting" : "aws.amazon.com" } { "_id" : 4, "domainName" : "test4.com", "hosting" : "hostgator.com" } { "_id" : 5, "domainName" : "test5.com", "hosting" : "aws.amazon.com" } { "_id" : 6, "domainName" : "test6.com", "hosting" : "cloud.google.com" } { "_id" : 7, "domainName" : "test7.com", "hosting" : "aws.amazon.com" } { "_id" : 8, "domainName" : "test8.com", "hosting" : "hostgator.com" } { "_id" : 9, "domainName" : "test9.com", "hosting" : "cloud.google.com" } { "_id" : 10, "domainName" : "test10.com", "hosting" : "godaddy.com" } ... { "_id" : 100, "domainName" : "test10.com", "hosting" : "godaddy.com" }
然后聚合操作为:
db.domain.aggregate(
{
$match : {_id:{$lt:10}}
},
{
$group : {_id : "$hosting", total : { $sum : 1 }}
},
{
$sort : {total : -1}
}
);
输出:
{ "_id" : "aws.amazon.com", "total" : 4 }
{ "_id" : "hostgator.com", "total" : 3 }
{ "_id" : "cloud.google.com", "total" : 2 }
{ "_id" : "godaddy.com", "total" : 1 }
使用spring data:
@Repository public class DomainDaoImpl implements DomainDao { @Autowired MongoTemplate mongoTemplate; public List<HostingCount> getHostingCount() { Aggregation agg = newAggregation( match(Criteria.where("_id").lt(10)), group("hosting").count().as("total"), project("total").and("hosting").previousOperation(), sort(Sort.Direction.DESC, "total") ); //Convert the aggregation result into a List AggregationResults<HostingCount> groupResults = mongoTemplate.aggregate(agg, Domain.class, HostingCount.class); List<HostingCount> result = groupResults.getMappedResults(); return result; }