gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:13:53 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于MongoDB 聚合 - 如何获取一个事件在一周中每天发生多少次的百分比值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47332116/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com