如何按群组mongodb制作结果

时间:2015-12-09 03:35:55

标签: mongodb mongodb-query aggregation-framework

我是mongodb的新手,我在mongodb的群组数据方面很难。 例如,我有这样的文档:

{
    School: S1
    Department: D1
    Class: C1
    Code: code1
    Time: 7h
},

{
    School: S1
    Department: D1
    Class: C1
    Code: code1
    Time: 8h
},

{
    School: S1
    Department: D1
    Class: C1
    Code: code2
    Time: 7h
},
{
    School: S1
    Department: D1
    Class: C2
    Code: code2
    Time: 7h
},
{
    School: S2 
    Department: D2
    Class: C3
    Code: code1
    Time: 8h
},
{
    School: S2
    Department: D2
    Class: C4
    Code: code2
    Time: 8h
},
{
    School: S2
    Department: D2
    Class: C5
    Code: code3
    Time:9h
}

预期结果的例子:

[
S1: {
    D1: {
        C1: {
            code1: {
                7h : 1,
                8h : 1
            },
            code2: {
                7h: 2
            }

        },
        C2: {
            code2: {
                7h : 1
            }
        }
    }       
},

S2: {
    D2: {
        C3: {
            code1: {
                8h: 1
            }                           
        },

        C4: {
            code2: {
                8h : 1
            }
        },

        C5: {
            code3: {
                9h: 1
            }
        }
    }
}

我不知道我在哪里开始写查询。

任何人都可以为此解决问题。

非常感谢!

1 个答案:

答案 0 :(得分:2)

您需要使用$addToSet创建元素数组,并使用一些$group来解决此问题。

看起来像:

db.insertTest.aggregate([{$group: {_id: {School: "$School", Department: "$Department", Class: "$Class", Code: "$Code", Time: "$Time"}, countTime:{$sum:1}}}, {$group: {_id:{School:"$_id.School", Department: "$_id.Department", Class: "$_id.Class", Code: "$_id.Code"}, Times: {$addToSet: {Time: "$_id.Time", countTime:"$countTime"}}}}, {$group: {_id:{School:"$_id.School", Department: "$_id.Department",Class: "$_id.Class"}, Codes: {$addToSet: {Code:"$_id.Code", Times:"$Times"}}}}])

第一组计算相同小时数,第二组创建包含小时及其计数的数组,第三组创建代码数组和前一阶段。