【发布时间】:2016-02-27 17:18:45
【问题描述】:
鉴于此 MongoDB 集合:
[
{ client: 'client1', type: 'Defect', time: 5 },
{ client: 'client1', type: 'Test', time: 5 },
{ client: 'client2', type: 'Management', time: 3 },
{ client: 'client2', type: 'Defect', time: 3 },
{ client: 'client3', type: 'Test', time: 4 }
]
我想从每个 issue_type 中获得总和,如下所示:
{
client1: { 'Defect': 5, 'Test': 5 },
client2: { 'Management': 3, 'Defect': 3 },
client3: { 'Test': 4 }
}
我一直在尝试使用聚合框架(以替换现有的 map/reduce)来做到这一点,但只能获得像这样的组合的计数:
{ '_id': { client: 'Client1', class: 'Defect' }, sum: 5 }
{ '_id': { client: 'Client1', class: 'Test' } count: 5 }
{ '_id': { client: 'Client2', class: 'Management' }, count: 3 }
{ '_id': { client: 'Client2', class: 'Defect' }, count: 3 }
{ '_id': { client: 'Client3', class: 'Test' }, count: 4 }
这很简单,可以通过编程方式简化为所需的结果,但我希望能够将其留给 MongoDB。
对于任何可能提供的帮助,非常感谢!
编辑
我正在添加这个聚合组
db.getCollection('issues').aggregate(
[
{
$group:
{
_id: {component:"$client"},
totalTime:{$sum: "$time" }
}
}
]
)
【问题讨论】:
-
您的值是字符串而不是数字。如果您有两个具有相同键/值对的文档,例如
{ client: 'client1', type: 'Defect', time: '5' },该怎么办?你想在这里做什么? -
您运行的是哪个版本的 MongoDB?
-
请发布您的聚合代码,以便我们根据您目前的情况为您提供帮助。
-
@user3100115 我想在客户端类型中对所有小时进行总计。我正在阅读一个包含问题时间估算列表的 csv,我想获得一些分析信息。
-
@Saleem mongod 版本:3.0.9
标签: mongodb mapreduce mongodb-query aggregation-framework