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

MongoDB聚合-如何获取一周中每天事件发生次数的百分比值,mongodb,percentage,Mongodb,Percentage,我是一个MongoDB noob,所以如果我的问题很愚蠢,请不要评判我:p 我试图从MongoDB获得一些结果,以创建一个表格,显示我每周每天玩某个游戏的百分比统计数据(每天所有游戏合计=100%)。这是我对数据库的JSON导入: [ {"title":"GTA","date":"2017-11-13"}, {"title":"GTA","date":"2017-11-13"}, {"title":"BattleField","date":"2017-11-13"}, {"title":"Bat

我是一个MongoDB noob,所以如果我的问题很愚蠢,请不要评判我: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获得如此高的百分比结果吗?

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

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