按日期Mongodb多键聚合(来自时间戳)

时间:2017-05-03 01:27:48

标签: mongodb mongodb-query aggregation-framework

我有一个mongodb集合,有数百万条关于交易的记录。我想创建一个按日期和分辨率聚合的查询。

我的文档如下:

{
    "_id": "Dan",
    "finish_date": "2017-01-02 15:23:45.234Z",
    "resolution": "canceled"
}
{
    "_id": "John",
    "finish_date": "2017-01-02 18:54:19.090Z",
    "resolution": "completed"
}
{
    "_id": "Pete",
    "finish_date": "2017-01-02 19:11:27.418Z",
    "order_resolution": "completed"
}

我希望查询输出看起来像:

{
    "2017-01-02" : {
        "canceled": 1,
        "completed": 2,
    }
}
{
    "2017-01-03" : {
        "completed": 5,
    }
}

这甚至可能吗?目前,我的输出如下:

{
    "_id" : {
        "curDate" : "2017-01-02",
        "reason" : "canceled"
    },
    "count" : 1.0
}
    "_id" : {
        "curDate" : "2017-01-02",
        "reason" : "completed"
    },
    "count" : 2.0
}
{
    "_id" : {
        "curDate" : "2017-01-03",
        "reason" : "completed"
    },
    "count" : 5.0
}

查询如下:

db.collection.aggregate(
    [
        {
            "$match": { 
                "finish_date": { 
                    "$gt": new Date("2017-01-02"), 
                    "$lt": new Date("2017-01-08") 
                }
            }
        },
        {
            "$group" : {
                _id : {
                    curDate: {
                        $substr: ["$finish_date", 0, 10]
                    },
                    reason: "$resolution"
                },
                count: { "$sum": 1 }
            }
        },
        {
            "$sort": { "_id.curDate": 1, "_id.reason": 1 }
        }
    ]
)

1 个答案:

答案 0 :(得分:0)

您可以使用$arrayToObject版本中提供的新运算符3.4.4和以下聚合查询。

<{>} $group curDate并将reasoncount值推送到reasoncount数组。

$zip reasoncount数组值一起后跟$arrayToObject来创建reasoncount结构。

在保留先前curDatereason结构的同时创建count结构的逻辑相同。

db.collection.aggregate(
    [
        {$match:{finish_date:{$gt: new Date("2017-01-02"),$lt: new Date("2017-01-08")}}},
        {$group:{_id:{curDate:{$substr:["$finish_date",0,10]},reason:"$resolution"},count:{$sum: 1}}},
        {$sort:{"_id.curDate":1,"_id.reason":1}},
        {$group:{_id:"$_id.curDate", reasoncount:{$push:{reason:"$_id.reason",count:"$count"}}}},
        {$addFields:{reasoncount: {$arrayToObject:{$zip:{inputs:["$reasoncount.reason", "$reasoncount.count"]}}}}},
        {$group:{_id:null, result:{$push:{curDate:"$_id",reasoncount:"$reasoncount"}}}},
        {$addFields:{result: {$arrayToObject:{$zip:{inputs:["$result.curDate", "$result.reasoncount"]}}}}}
    ]
)