dav*_*idM 3 percentage mongodb
我是 MongoDB 菜鸟,所以如果我的问题很愚蠢,请不要评判我:P\n我试图从 MongoDB 获取一些结果来创建一个表,该表将显示我每周每天玩某个游戏的百分比统计数据(所有游戏)每天在一起 = 100%)。这是我的数据库 JSON 导入:
\n\n[\n{"title":"GTA","date":"2017-11-13"},\n{"title":"GTA","date":"2017-11-13"},\n{"title":"BattleField","date":"2017-11-13"},\n{"title":"BattleField","date":"2017-11-13"},\n{"title":"BattleField","date":"2017-11-14"}\n]\nRun Code Online (Sandbox Code Playgroud)\n\n我编写了一个聚合,按天对结果进行分组,并计算每天玩游戏的总次数\xe2\x80\xa6:
\n\ndb.games.aggregate([\n { $project: { _id: 0, date : { $dayOfWeek: "$date" }, "title":1} },\n { $group: { _id: {title: "$title", date: "$date"}, total: {$sum: 1} } }, \n { $group: { _id: "$_id.date", types: {$addToSet: {title:"$_id.title", total: "$total"} } } }\n])\nRun Code Online (Sandbox Code Playgroud)\n\n\xe2\x80\xa6 这是我现在从 MongoDB 得到的:
\n\n/* 1 */\n{\n "_id" : 3, \n "types" : [\n {\n "title" : "BattleField",\n "total" : 1.0\n }\n ]\n},\n\n/* 2 */\n{\n "_id" : 2, \n "types" : [\n {\n "title" : "GTA",\n "total" : 2.0\n },\n {\n "title" : "BattleField",\n "total" : 2.0\n }\n ]\n}\nRun Code Online (Sandbox Code Playgroud)\n\n我需要得到的是一个如下所示的表:
\n\n Monday Tuesday\nGTA 50,00% 0%\nBattleField 50,00% 100%\nRun Code Online (Sandbox Code Playgroud)\n\n您能告诉我如何从 Mongo 获得这样的百分比结果吗?
\n您的尝试非常接近解决方案!以下内容应该为您指明正确的方向:
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"
])
Run Code Online (Sandbox Code Playgroud)
结果:
{
"title" : "BattleField",
"percentage" : 0.5,
"day" : "Tue"
}
{
"title" : "GTA",
"percentage" : 0.5,
"day" : "Tue"
}
{
"title" : "BattleField",
"percentage" : 1.0,
"day" : "Wed"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2719 次 |
| 最近记录: |