首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法使mongodb $group与objectID和$match一起工作

无法使mongodb $group与objectID和$match一起工作
EN

Stack Overflow用户
提问于 2016-09-08 21:04:31
回答 1查看 588关注 0票数 0
代码语言:javascript
复制
WhiskeySchema.statics.count = function (data){
    var distillerIds = data.map(function (a) {
        return a.distiller._id;
    });
    return Whiskey
        .aggregate([
            { $group: {
                // Group by fields to match on distiller
                _id: { distiller: '$distiller'},
                // Count number of matching whiskeys for the group
                count: { $sum:  1 }
            }},
                {
                    $match: {
                        distiller : {
                            $in: distillerIds
                        }
                    }
                }
    ])
    .execAsync()
    .then(function(countedData){
        console.log('counted data :', countedData)
        return countedData;
    })
    .catch(function(err){
        console.log('whiskey count err : ', err);
    })
};

蒸馏/ $distiller是一种芒果ObjectID。一个推荐信。

我想通过特定的in来查找,就像我在比赛中所做的那样。

然后,在这些匹配的结果中,我想在威士忌中的蒸馏器Id相同的情况下对它们进行分组,并对它们进行计数。(试图计算每个酒厂的威士忌总数)。

匹配正常工作,但是当我包含组和计数时--我一直得到一个返回给countedData的空数组。

代码语言:javascript
复制
counted data : []
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-09 05:39:50

聚合的组部分不正确,请将其更改为:

代码语言:javascript
复制
.aggregate([
{
    $match: {
        distiller : {
            $in: distillerIds
        }
    }
}
{ $group: {
    // Group by fields to match on distiller
    _id: '$distiller',
    // Count number of matching whiskeys for the group
    count: { $sum:  1 }
}}

我还移动了匹配,最好在第一个管道阶段进行匹配,这样它就使用了集合中的索引。当进一步在管道中时,不能使用任何索引。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39400182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档