【问题标题】:MongoDB $group aggregationMongoDB $组聚合
【发布时间】:2018-02-08 13:25:05
【问题描述】:

我有这样的收藏

OrgName EmpId   Domain    Date
Google  12345   ABC   2017/01/01
Google  12345   XYZ   2017/02/01 
Google  67890   ABC   2017/03/01
Google  45678   ABC   2017/03/02
Yahoo   69875   HGF   2017/03/02
Google  45678   XYZ   2017/03/03
Google  45678   XYZ   2017/03/03
Google  12345   XYZ   2017/03/03
Google  12345   ABC   2017/03/04
Google  12345   ABC   2017/04/05

我需要获取具有最大“域”计数的员工,并且必须同时在“ABC”和“XYZ”域 GROUPBY OrgName 中。

我正在使用以下查询:

db.Collection1.aggregate([{ "$match" : { "$or" : [ { "Domain": "ABC"},{ "Domain": "XYZ"}]}},
{
    $group :{ "_id": {"OrgName" : "$OrgName", "EmpId" : "$EmpId",
        "Domain" : "$Domain"},
            count:{ $sum : 1 },
            "participantData" : { "$push" : { "EmpId" : "$EmpId" , "Domain" : "$Domain"}}}},
    {$sort:{"count":-1}},
     {$limit: 10}
],{ allowDiskUse: true })

在上面的示例中,预期结果:employee_id=12345 同时出现在“ABC”和“XYZ”域中计数为 5(即 12345.ABC = 3和 12345.XYZ=2)。

【问题讨论】:

  • 这里有问题吗?
  • @KirkLarkin 是的!我已经更新了问题。问题:我需要通过 OrgName,EmpId 获取 Count(Domain) where Domain = ABC and Domain = XYZ Group

标签: mongodb mongodb-query aggregation-framework aggregation


【解决方案1】:

你可以试试下面的查询。

以下查询 $group 按 OrgName、EmpId 后跟 $match 以过滤参与者数组包含“ABC”和“XYZ”值的文档。

$sort按count过滤后的数据,输出前10个值。

db.collection.aggregate([
  {"$match":{"$or":[{"Domain":"ABC"},{"Domain":"XYZ"}]}},
  {"$group":{
    "_id":{"OrgName":"$OrgName","EmpId":"$EmpId"},
    "count":{"$sum":1},
    "participantData":{"$push":{"EmpId":"$EmpId","Domain":"$Domain"}}
  }},
  {"$match":{"participantData.Domain":{"$all":["ABC","XYZ"]}}},
  {"$sort":{"count":-1}},
  {"$limit":10}
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 2014-12-01
    • 2023-03-21
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多