Mongodb聚合查询帮助 - 使用多个字段进行分组并转换为数组

时间:2014-02-05 17:40:13

标签: mongodb mongodb-query aggregation-framework transformation

我在mongodb集合中有以下文档

[{quarter:'Q1',project:'project1',user:'u1',cost:'100'},
{quarter:'Q2',project:'project1',user:'u2',cost:'100'},
{quarter:'Q3',project:'project1',user:'u1',cost:'200'},
{quarter:'Q1',project:'project2',user:'u2',cost:'200'},
{quarter:'Q2',project:'project2',user:'u1',cost:'300'},
{quarter:'Q3',project:'project2',user:'u2',cost:'300'}]

我需要生成一个输出,该输出将基于季度和项目的成本相加,并将其放入格式中,以便可以在Extjs图表中进行渲染。

[{quarter:'Q1','project1':100,'project2':200,'project3':300},
{quarter:'Q2','project1':100,'project2':200,'project3':300},
{quarter:'Q3','project1':100,'project2':200,'project3':300}]

我尝试了各种聚合的排列和组合,但无法真正想出一个管道。非常感谢您的帮助或指导

1 个答案:

答案 0 :(得分:0)

您的费用数据似乎是字符串,这没有帮助,但假设您就是这样:

主要组件是文档投影中的$cond运算符,假设您的数据较大并且您想对结果进行分组:

db.mstats.aggregate([
    // Optionaly match first depending on what you are doing

    // Sum up cost for each quarter and project
    {$group: {_id: { quarter: "$quarter", project: "$project" }, cost: {$sum: "$cost" }}},

    // Change the "projection" in $group, using $cond to add a key per "project" value
    // We use $sum and the false case of 0 to fill in values not in the row.
    // These will then group on the key adding the real cost and 0 together.
    {$group: { 
        _id: "$_id.quarter",
        project1: {$sum: {$cond:[ {$eq: [ "$_id.project", "project1" ]}, "$cost",  0 ]}},
        project2: {$sum: {$cond:[ {$eq: [ "$_id.project", "project2" ]}, "$cost",  0 ]}}
    }},

    // Change the document to have the "quarter" key
    {$project: { _id:0, quarter: "$_id", project1: 1, project2: 1}},

    // Optionall sort by quarter
    {$sort: {quarter: 1 }}
])

因此,在进行初始分组后,使用$cond更改文档以确定密钥的值是否将进入新的密钥名称。基本上,这会询问project的当前值是否为“project1”,然后将cost值放入此project1键。等等。

当我们在没有匹配时将0值放入此新文档密钥时,我们需要再次对结果进行分组以合并文档。排序是可选的,但可能是您想要的图表。

当然,您必须动态构建它,并可能查询所需的project键。但是否则这应该是你正在寻找的。