我不确定这是否是一个有效的问题。我已经开始研究 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