【问题标题】:Mongo Aggregate group two field in a single queryMongo 在单个查询中聚合组两个字段
【发布时间】:2018-08-07 19:49:22
【问题描述】:

我有这样的查询。

db.getCollection('wifi_sessions_90').aggregate([
    { $match: {Datetime: {$gt: new Date(new Date(ISODate().getTime() - 1000 * 60 * 60 * 24 * 14))}}},
    {
        $project:{
            uploadType:{
                    $switch:{
                        branches:[
                        {
                                case:{ $gt : ['$Upload', 2147483648] },
                                then: "> 2Gb"
                        },
                        {
                                case:{ $and : [{ $gt : ['$Upload', 1073741824] }, { $lt : ['$Upload',2147483648] }]},
                                then: "1 - 2Gb"
                        },
                        {
                                case:{ $and : [{ $gt : ['$Upload', 524288000] }, { $lt : ['$Upload',1073741824] }]},
                                then: "500Mb - 1Gb"
                        }
                        ],
                        default: "< 500Mb"
                    }
            },
            downloadType:{
                    $switch:{
                        branches:[
                        {
                                case:{ $gt : ['$Download', 2147483648] },
                                then: "> 2Gb"
                        },
                        {
                                case:{ $and : [{ $gt : ['$Download', 1073741824] }, { $lt : ['$Download',2147483648] }]},
                                then: "1 - 2Gb"
                        },
                        {
                                case:{ $and : [{ $gt : ['$Download', 524288000] }, { $lt : ['$Download',1073741824] }]},
                                then: "500Mb - 1Gb"
                        }
                        ],
                        default: "< 500Mb"
                    }
            }
        }
    }
])

它将每个文档“上传”和“下载”分类到自己的类别。然后我将它分组例如上传

{ $group :
    {
        _id :
        {
            uploadType : '$uploadType'
        },
        count : { $sum: 1 }
    }
}

有没有一种方法可以在单个查询中实现“下载”?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以在分组之前将它们拉入数组。

    类似

    [
     {"$project":{
        "types":[
          {"name":"uploadType",
          "value":{"$switch":{...}}},
          {"name":"downloadType",
           "value":{"$switch":{...}}}
        ]
     }},
     {"$unwind":"$types"},
     {"$group":{
       "_id":{"name":"$types.name","value":"$types.value"},
       "count":{"$sum":1}
     }}
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2015-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 2020-06-06
      • 1970-01-01
      相关资源
      最近更新 更多