【问题标题】:MongoDB Spring Data how can I aggregate count from multiple fields?MongoDB Spring Data 如何汇总多个字段的计数?
【发布时间】:2018-03-26 19:06:35
【问题描述】:

假设有一些数据是这样的:

{
"orderId": 1,
    "manager" : [ 
        {
            "userId" : "UserId1"
        }
    ],
    "employee" : [ 
        {
            "userId" : "UserId3"
        }
    ]
}

{
"orderId": 2,
    "manager" : [ 
        {
            "userId" : "UserId1"
        }
    ],
    "employee" : [ 
        {
            "userId" : "UserId2"
        }
    ]
}

{
"orderId": 3,
    "manager" : [ 
        {
            "userId" : "UserId1"
        }
    ],
    "employee" : [ 
        {
            "userId" : "UserId2"
        }
    ]
}

结果应该是:

{  
   "Agg":[  
      {  
         "userId":"UserId1",
         "total":3
      },
      {  
         "userId":"UserId2",
         "total":2
      },
      {  
         "userId":"UserId3",
         "total":1
      }
   ]
}

我想获取参与某个进程的用户 ID 的所有聚合计数。我需要从“员工”和“经理”对象中按用户 ID 分组并对它们求和。我只能从一个列表中按 userId 分组:

Aggregation agg = newAggregation(
   match(Criteria.where("project").is("project")),
   unwind("manager"),
   group("manager.userId").count().as("total"),
   project("total").and("userId").previousOperation(),
   sort(Sort.Direction.DESC, "total")
);

如何汇总“经理”和“员工”字段的计数?

【问题讨论】:

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


    【解决方案1】:

    使用$concatArrays

    Aggregation agg = newAggregation(
       match(Criteria.where("project").is(project)),
       project("employee", "manager"),         
       project().and("manager").concatArrays("employee").as("merged"),
       unwind("merged"),
       group("merged.userId").count().as("total"),
       project("total").and("userId").previousOperation(),
       sort(Sort.Direction.DESC, "total")
    );
    

    【讨论】:

      【解决方案2】:

      尝试类似:

       "$group' : { 
        '_id' : '$id', 
        'totalManager' : { '$sum' : '$manager.total' },
        'totalemployee' : { '$sum' : '$employee.total' }
      }  }
       { "$project" : {
        'totalManager' : '$totalManager',
        'totalemployee' : '$totalemployee',
        'totalSum' : { '$add' : [ '$totalManager', '$totalemployee' ] },
       }
      

      【讨论】:

        猜你喜欢
        • 2018-07-13
        • 2016-01-08
        • 1970-01-01
        • 1970-01-01
        • 2013-07-13
        • 2017-06-03
        • 2021-07-03
        • 2013-06-07
        • 1970-01-01
        相关资源
        最近更新 更多