mongo按月汇总并返回结果

时间:2015-12-24 09:13:23

标签: mongodb meteor aggregation-framework

我有这个......

$group: {
        '_id': this.userId,
        'hours': {
            $sum: '$hours'
        },
        'magazines': {
            $sum: '$magazines'
        },
        'brochures': {
            $sum: '$brochures'
        },
        'books': {
            $sum: 'books'
        }
    }
}, {
    $project: {
        hours: '$hours',
        magazines: '$magazines',
        brochures: '$brochures',
        books: '$books'
    }

...返回上述字段的总和。

我想要做的是,返回特定用户的总时长,例如,小时数,分为几个月。

类似的东西:

January:
    userId:
        hours: 10
        magazines: 10
        ....
February:
    userId:
        hours:2
        magazines: 2
etc

2 个答案:

答案 0 :(得分:2)

使用以下聚合管道,该管道使用 date aggregation operators $year $month 来获取每个用户的给定属性的总和按月分组:

var pipeline = [
    {
        "$group": {
            "_id": {
                "userId": "$userId"
                "year": { "$year": "$date" }
                "month" { "$month": "$date" }
            },
            'hours': {
                $sum: '$hours'
            },
            'magazines': {
                $sum: '$magazines'
            },
            'brochures': {
                $sum: '$brochures'
            },
            'books': {
                $sum: 'books'
            }
        ]
    }
]

db.collection.aggregate(pipeline);

要获取将月份和userId值转换为键的确切架构,请使用 map() 返回的光标中的 aggregate() 方法strong>方法:

var result = db.collection.aggregate(pipeline).map(function (doc){
    var obj = {};
    obj[doc._id.month][doc._id.userId]["hours"] = doc.hours;
    obj[doc._id.month][doc._id.userId]["magazines"] = doc.magazines;
    obj[doc._id.month][doc._id.userId]["brochures"] = doc.brochures;
    obj[doc._id.month][doc._id.userId]["books"] = doc.books;

    return obj;
});

printjson(result);

答案 1 :(得分:0)

这是有效的解决方案。回答MongoDB-User group

[{
        $group: {
            _id: {
                $month: "$createdAt"
            },
            hours: {
                $sum: "$hours",
            },
            magazines: {
                $sum: "$magazines"
            },
            brochures: {
                $sum: "$brochures"
            },
            books: {
                $sum: "$books"
            }
        }
}]