spring data mongodb:按域名汇总

时间:2018-01-30 21:46:27

标签: spring mongodb aggregation-framework spring-data-mongodb

我有包含id,domain的集合。在集合中,同一个域保存了多次。我想聚合并得到像

这样的结果 google.com 4 times.com 5

我的代码

 public List<DomainDTO> domainAggregation() {

        Aggregation pipeline = newAggregation(
                group(fields("id","domain")),
                group("domain").count().as("count"),
                sort(Sort.Direction.DESC, previousOperation(), "domain")
        );


        AggregationResults groupResults = mongoTemplate.aggregate(
                pipeline, Domains.class, DomainDTO.class);

        List<DomainDTO> domainReport = groupResults.getMappedResults();

        return domainReport;
    }

DomainDTO包含

 private String domain;    
    private Integer count;

域实体包含

 private String id;  
    private String searchId;    
    private String domain;
    private Date searchDate;
    private String searchName;
    private Integer count;

结果json是

{
    "domain": null,
    "count": 2
  },
  {
    "domain": null,
    "count": 1
  },
  {
    "domain": null,
    "count": 2
  },
  {
    "domain": null,
    "count": 48
  },

域名未传递,且未排序。找不到bug。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您当前的查询输出类似

的内容
{ "$group" : { 
   "_id" : { "id" : "$id" , "domain" : "$domain"}
} } , 
{ "$group" : { "_id" : "$_id.domain" , "count" : { "$sum" : 1}}} , 
{ "$sort" : { "_id" : -1 , "_id.domain" : -1}}

我相信你想要像

这样的东西
{ "$group" : { "_id" : "$domain" , "count" : { "$sum" : 1}}} , 
{ "$sort" : { "_id" : -1}}

聚合Java代码:

Aggregation pipeline = newAggregation(
   group("domain").count().as("count"),
   sort(Sort.Direction.DESC, previousOperation())
);

您需要$project阶段将_id映射回domain课程中的DomainDTO

Aggregation pipeline = newAggregation(
   group("domain").count().as("count"),
   sort(Sort.Direction.DESC, previousOperation()),
   project(bind("domain", "_id")).andExclude("_id").andInclude("count")
);

Mongo Shell

{ "$group" : { "_id" : "$domain" , "count" : { "$sum" : 1}}} , 
{ "$sort" : { "_id" : -1}},                   
{ "$project" : { "domain" : "$_id" , "_id" : 0 , "count" : 1}