代码之家  ›  专栏  ›  技术社区  ›  Armen Arzumanyan

spring data mongodb:按域名进行总和聚合

  •  0
  • Armen Arzumanyan  · 技术社区  · 7 年前

    我有一个包含id、域的集合。在集合中,同一域多次保存。我想聚合并得到如下结果

    谷歌。com 4 《泰晤士报》。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;
        }
    

    域组成

     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
      },
    

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   s7vr    7 年前

    当前查询输出如下内容

    { "$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映射回的阶段\u 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}