ruby-on-rails - MongoDB聚合在分组时将键推为零
问题描述
我不确定这是否是一个有效的问题。我已经开始研究 mongodb 聚合。我必须为每天、每周、每月的数据制作图表。
我根据提供的日期使用“ $dayOfMonth ”、“ $week ”、“ $month ”进行分组。例如,如果起点和终点的日期差异小于或等于 6,我每天使用“ $dayOfMonth ”进行分组,如果起点和终点的日期差异大于 6 且小于 30,则对“ $week ”进行分组,并且如果差异大于 30 则按月“ $month ”进行分组。
我在“ $match ”中传递日期。如果不存在分组,是否可以按 0 作为键。
示例 - from_date = "01/01/2018" to_date = "30/6/2018" 因此分组将按月进行。假设我没有第 3 个月、第 4 个月和第 5 个月的日期。我想在嵌套键中推送 0 作为值。
output = [
{"_id": "01/01/2018", "counter":12},
{"_id": "01/02/2018", "counter": 15},
{"_id":"01/06/2018", counter: 10}
]
expected_output =
[
{"_id": "01/01/2018", "counter":12},
{"_id": "01/02/2018", "counter": 15},
{"_id":"01/03/2018", counter: 0},
{"_id":"01/04/2018", counter:0},
{"_id":"01/05/2018", counter: 0},
{"_id":"01/06/2018", counter: 10}
]
我正在使用 Rails 和 Mongoid Gem。我正在使用的查询
converted = Analytics::Conversion::PharmacyPrescription.collection.aggregate([
{ "$match" => {
"organisation_id" => org_id.to_s,
"date" => {
"$gte" => from_date,
"$lte" => to_date
},
"role_ids" => {"$in" => [role_id, "$role_ids"]}
}
},{
"$project" => {
"total_count" => 1,
"converted_count" => 1,
"not_converted_count" => 1,
"total_invoice_amount" => 1,
"user_id" => 1,
"facility_id" => 1,
"organisation_id" => 1,
"date" => 1,
}
},{
"$group" => {
"_id" => { "#{groupby}" => "$date" },
"total_count" => {"$sum" => "$total_count"},
"converted_count" => { "$sum" => "$converted_count" },
"not_converted_count" => { "$sum" => "$not_converted_count"},
}
}
]).to_a
解决方案
聚合框架只能聚合您拥有的文档。您实际上是在要求它为不存在的文档添加组,但它无法“知道”要添加哪些组。
我要做的是按照您的方式运行查询,然后根据所选粒度“传播”日期单位(在您的示例中,它将是 01/01/2018、01/02/2018、01/03/2018 , 01/04/2018, 01/05/2018, 01/06/2018,然后运行一个简单的函数,该函数将为每个缺失的单元添加一个条目。
推荐阅读
- ssh - 代理链、nla 和 rdekstop
- sql-server - 使用 unixODBC 的 isql 访问 sql server
- c# - .NET 和 Angular 项目
- jenkins - Jenkins 在 sh 中使用脚本变量
- react-native - 我如何在同一个 webview 中打开 webview 链接?
- solr - 无法解释的 SOLR 查询
- php - 如何在 Gitlab CI 中为基于 Docker 的 PHP 应用程序创建测试管道
- python - 隐藏嵌入式窗口栏 pyqt5/隐藏 selenium 窗口标题栏而不全屏 & 使 pyqt5 嵌入式窗口不可拖动/调整大小
- firebase - 从云存储中检索数据时出现问题
- python-3.x - 如何让 mypy 忽略或识别动态添加的属性?