【发布时间】:2014-09-30 23:40:18
【问题描述】:
我有多个具有此架构的文档,每个文档每天针对每个产品:
{
_id:{},
app_id:'DHJFK67JDSJjdasj909',
date:'2014-08-07',
event_count:32423,
event_count_per_type: {
0:322,
10:4234,
20:653,
30:7562
}
}
我想获取特定日期范围内每个 event_type 的总和。
这是我正在寻找的输出,其中每个事件类型已在所有文档中求和。 event_count_per_type 的键可以是任何东西,所以我需要一些可以循环遍历它们的东西,而不必隐含它们的名称。
{
app_id:'DHJFK67JDSJjdasj909',
event_count:324236456,
event_count_per_type: {
0:34234222,
10:242354,
20:456476,
30:56756
}
}
到目前为止,我已经尝试了几个查询,这是迄今为止我得到的最好的,但是子文档值没有相加:
db.events.aggregate(
{
$match: {app_id:'DHJFK67JDSJjdasj909'}
},
{
$group: {
_id: {
app_id:'$app_id',
},
event_count: {$sum:'$event_count'},
event_count_per_type: {$sum:'$event_count_per_type'}
}
},
{
$project: {
_id:0,
app_id:'$_id.app_id',
event_count:1,
event_count_per_type:1
}
}
)
我看到的输出是 event_count_per_type 键的值 0,而不是对象。我可以修改架构,使键位于文档的顶层,但这仍然意味着我需要在每个键的组语句中都有一个条目,因为我不知道键名是什么,所以我不能做。
任何帮助都将不胜感激,如果需要,我愿意更改我的架构并尝试使用 mapReduce(尽管从文档看来性能很差。)
【问题讨论】:
-
如果您不知道子文档中的键名,那么您不能通过聚合来执行此操作(但您可以使用 map-reduce)。您确定键名可以是 anything 吗?还是只能是一定范围内的数字?可以是“富”吗?还是只能是 0 到 59 之间的数字或类似的数字?
-
@AsyaKamsky 它将是 0 到 100 之间的整数
标签: javascript mongodb mapreduce mongodb-query aggregation-framework