MongoDB聚合返回值为键的嵌套组?

时间:2013-02-21 13:40:26

标签: mongodb

我的文件如下:

{
        "_id" : "Tvq579754r",
        "Status" : "passed",
        "Title" : "up08c",
        "ProjectID" : "Tvq5p",
        "Version" : "1.0.0",
        "Platform" : "platform_x",
        "METRIC_A" : 11114.85,
        "METRIC_B" : 68.9,
        "METRIC_C" : 65.35,
},
{
        "_id" : "Tvq579755r",
        "Status" : "passed",
        "Title" : "up09c",
        "ProjectID" : "Tvq5p",
        "Version" : "1.0.0",
        "Platform" : "platform_x",
        "METRIC_A" : 21114.85,
        "METRIC_B" : 168.9,
        "METRIC_C" : 165.35,
},
{
        "_id" : "Tvq579756r",
        "Status" : "passed",
        "Title" : "up09c",
        "ProjectID" : "Tvq5p",
        "Version" : "1.0.0",
        "Platform" : "platform_x",
        "METRIC_A" : 31114.85,
        "METRIC_B" : 268.9,
        "METRIC_C" : 265.35,
}

现在,通过$avg$sumMETRIC_分组,我可以对ProjectIDVersionPlatform字段进行分组并获取问题和Title,但我想在聚合框架内做的事情(如果可能)是返回使用分组值作为键的对象,例如:

{ 
        <Project ID> : {
                <Version> : {
                        <Platform> : {
                                <Title> : {
                                        "METRIC_A": <sum of METRIC_A>,
                                        "METRIC_B": <sum of METRIC_B>,
                                        "METRIC_C": <sum of METRIC_C>,
                                }
                        }
                }
        }
}

或者,在我的例子中:

{ 
        'Tvq5p' : {
                '1.0.0' : {
                        'platform_x' : {
                                'up08c' : {
                                        "METRIC_A": 11114.85,
                                        "METRIC_B": 68.9,
                                        "METRIC_C": 65.35,
                                },
                                'up09c' : {
                                        "METRIC_A": 52229.7,
                                        "METRIC_B": 437.8,
                                        "METRIC_C": 430.7,
                                }
                        }
                }
        }
}

一旦消费服务收到查询结果,我目前正在这样做,这不是非常慢或任何东西,但我只是觉得从Mongo那里走出来会很好。这甚至可能吗?

感谢。

1 个答案:

答案 0 :(得分:0)

在MongoDB中有group operation

db.records.group( {
   key: { 'platform_x': 1, 'title': 1 },
   reduce: function(cur, result) { 
     result.metric_a += cur.metric_a;
     result.metric_b += cur.metric_b;
     result.metric_c += cur.metric_c;
   },
   initial: { metric_a = 0, metric_b = 0, metric_c = 0 }
 } )

如果这不起作用,我建议Map Reduce