使用Mongo聚合计算集合中的文档数(特定值)

时间:2014-06-11 08:21:38

标签: mongodb mongoose

我的集合架构是:

var RecommendationSchema = new Schema({
    tagId: {
        type: ObjectId,
        ref: 'Tag'
    },
    recommenderID: {
        type: ObjectId,
        ref: 'User'
    },
    recommendedID: {
        type: ObjectId,
        ref: 'User'
    },
});

因此,每当有人推荐"时,我会在此集合中填写新文档。我想要做的是,看看谁拥有最多"建议"给定tagId的(文件)。到目前为止,我有:

recommendationModel.aggregate({
            $group: {
                _id: '$tagId',
                total_recommendations: {
                    $sum: 1
                }
            }
        },
        function(err, results) {
            if (err) {
                return next(err);
            }
            return res.send(results);
        }
    );

但这会产生:

     [ { _id: 539587cdd43cfb1f31c3b7a0, total_recommendations: 1 },
09:10:19 web.1  |   { _id: 539587ead43cfb1f31c3b7a5, total_recommendations: 1 },
09:10:19 web.1  |   { _id: 539587dbd43cfb1f31c3b7a2, total_recommendations: 2 },
09:10:19 web.1  |   { _id: 539587c9d43cfb1f31c3b79f, total_recommendations: 2 },
09:10:19 web.1  |   { _id: 539587c3d43cfb1f31c3b79e, total_recommendations: 2 } ]

所以它只是告诉我每个tagId有多少文档。我如何获得数据集,例如:

(伪)

tagId: 123456789
recommendedId: xyz
total_recommendations: 10

tagId: 123456789
recommendedId: abc
total_recommendations: 4

tagId: 123456789
recommendedId: mno
total_recommendations: 7

这是否可行(使用带有Node.js的Mongoose进行Mongo访问)?

1 个答案:

答案 0 :(得分:0)

要将tagId计数除以recommendedId,请将这两个字段放入_id的{​​{1}}中:

$group