小编Irf*_*fan的帖子

mongo $ sum在进行$ unwind时复合,然后在多个字段上进行$ group

我有以下文档结构

{
    "app_id": "DHJFK67JDSJjdasj909",
    "date": ISODate("2014-08-07T00:00:00.000Z"),
    "event_count": 100,
    "events": [
        { "type": 0,  "value": 12  },
        { "type": 10, "value": 24 },
        { "type": 20, "value": 36  },
        { "type": 30, "value": 43 }
    ],
    "unique_events": [
        { "type": 0,  "value": 5  },
        { "type": 10, "value": 8 },
        { "type": 20, "value": 12  },
        { "type": 30, "value": 56 }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我试图得到一个event_counts的总和,以及每种类型的unique_events和事件的值.这是我期望的输出类型,其中event_count以及每个事件和unique_events值已按类型求和.

{
    "app_id": "DHJFK67JDSJjdasj909",
    "date": ISODate("2014-08-07T00:00:00.000Z"),
    "event_count": 4345,
    "events": [
        { "type": 0,  "value": 624  },
        { …
Run Code Online (Sandbox Code Playgroud)

mongodb mongodb-query aggregation-framework

5
推荐指数
1
解决办法
2639
查看次数

MongoDB聚合汇总子文档上的每个键

我有这个架构的多个文档,每个文档是每天每个产品:

{
    _id:{},
    app_id:'DHJFK67JDSJjdasj909',
    date:'2014-08-07',
    event_count:32423,
    event_count_per_type: {
        0:322,
        10:4234,
        20:653,
        30:7562
    }
}
Run Code Online (Sandbox Code Playgroud)

我想得到特定date_range的每个event_type的总和.
这是我正在寻找的输出,其中每个事件类型已在所有文档中求和.event_count_per_type的键可以是任何东西,所以我需要一些可以遍历每个键的东西,而不是必须隐含它们的名字.

{
    app_id:'DHJFK67JDSJjdasj909',
    event_count:324236456,
    event_count_per_type: {
        0:34234222,
        10:242354,
        20:456476,
        30:56756
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,我一直在尝试几个查询,这是迄今为止我得到的最好的但是子文档值没有求和:

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
    }
}
)
Run Code Online (Sandbox Code Playgroud)

我看到的输出是event_count_per_type键的值为0,而不是对象.我可以修改架构,以便键是在文档的顶层,但将仍然意味着我必须组语句给每个密钥,因为我不知道密钥的名字会是什么一个条目我不能做.

任何帮助将不胜感激,如果需要,我愿意更改我的架构,并尝试mapReduce(尽管从文档中看起来表现不错.)

javascript mapreduce mongodb mongodb-query aggregation-framework

4
推荐指数
1
解决办法
2848
查看次数