MongoDB聚合 - 如何获取事件每周发生的次数的百分比值

时间:2017-11-16 14:23:45

标签: mongodb percentage

我是一个MongoDB菜鸟,所以如果我的问题很愚蠢,请不要判断我:P 我试图从MongoDB获得一些结果来创建一个表格,该表格将显示每周每天玩某个游戏的百分比统计数据(所有游戏每天一起= 100%)。这是我对数据库的JSON导入:

[
{"title":"GTA","date":"2017-11-13"},
{"title":"GTA","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-13"},
{"title":"BattleField","date":"2017-11-14"}
]

我编写了一个聚合,按日计算结果,并计算每天游戏的总次数......:

db.games.aggregate([
    { $project: { _id: 0, date : { $dayOfWeek: "$date" }, "title":1} },
    { $group: { _id: {title: "$title", date: "$date"}, total: {$sum: 1} } }, 
    { $group: { _id: "$_id.date", types: {$addToSet: {title:"$_id.title", total: "$total"} } } }
])

...这就是我现在从MongoDB获得的:

/* 1 */
{
    "_id" : 3, 
    "types" : [
        {
            "title" : "BattleField",
            "total" : 1.0
        }
    ]
},

/* 2 */
{
    "_id" : 2, 
    "types" : [
        {
            "title" : "GTA",
            "total" : 2.0
        },
        {
            "title" : "BattleField",
            "total" : 2.0
        }
    ]
}

我需要得到的是一个看起来像这样的表:

            Monday      Tuesday
GTA         50,00%      0%
BattleField 50,00%      100%

你能否告诉我如何从Mongo获得这样的百分比结果?

1 个答案:

答案 0 :(得分:2)

您的尝试非常接近解决方案!以下内容应指向正确的方向:

aggregate([
    { $project: { "_id": 0, "date" : { $dayOfWeek: "$date" }, "title": 1 } }, // get the day of the week from the "date" field
    { $group: { "_id": { "title": "$title", "date": "$date" }, "total": { $sum: 1 } } }, // group by title and date to get the total per title and date
    { $group: { "_id": "$_id.date", "types": { $push: { "title": "$_id.title", total: "$total" } }, "grandTotal": { $sum: "$total" } } }, // group by date only to get the grand total
    { $unwind: "$types" }, // flatten grouped items
    { $project: { "_id": 0, "title": "$types.title", "percentage": { $divide: [ "$types.total", "$grandTotal" ] }, "day": { $arrayElemAt: [ [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "$_id" ] } } }, // calculate percentage and beautify output for "day"
])

结果:

{
    "title" : "BattleField",
    "percentage" : 0.5,
    "day" : "Tue"
}
{
    "title" : "GTA",
    "percentage" : 0.5,
    "day" : "Tue"
}
{
    "title" : "BattleField",
    "percentage" : 1.0,
    "day" : "Wed"
}