【问题标题】:MongoDB aggregation - how to get a percentage value of how many times an event occurred per day of weekMongoDB聚合 - 如何获取事件每周发生次数的百分比值
【发布时间】:2017-11-17 07:12:58
【问题描述】:

我是 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 获得这样的百分比结果?

【问题讨论】:

    标签: mongodb percentage


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-08
      • 2020-03-19
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多