每个子文档的MongoDb聚合

时间:2015-02-02 16:12:51

标签: mongodb group-by aggregation-framework subdocument

我有这些收藏品,统计数据和物品。统计信息有一个项目作为子文档:

var ItemSchema = new Schema({ 
    type: String,
    created_at: Date,
    updated_at: {
        type: Date,
        default: Date.now()
    }
});

var StatsSchema = new Schema({ 
    item: {
        type: Schema.ObjectId,
        ref: 'Item'
    },
    url: String,
    date: Date,
    action: String,
    hourly: Number
});

我想通过item.type聚合统计分组。有可能吗?

我试过这样的事情,但没有运气:

db.stats.aggregate(
    { $project: { _id: 1, hourly: 1, action: 1, item: 1, type: '$item.type' } }, 
    { $group: { _id: { action: '$action', type: '$item.type' }, total: { $sum: '$hourly' } } }
)

1 个答案:

答案 0 :(得分:0)

您不应该需要管道的$project部分。 您应该从$group阶段

获得所需内容
db.stats.aggregate({ $group: { _id: "$item.type" , total: { $sum: '$hourly' } } });
相关问题