单个查询中的Mongo Aggregate第二组字段

时间:2018-08-07 11:30:00

标签: mongodb mongodb-query aggregation-framework

我有类似这样的查询。

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

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

1 个答案:

答案 0 :(得分:1)

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

类似

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