【问题标题】:Cannot get mongodb $group to work with an objectID and $match无法让 mongodb $group 使用 objectID 和 $match
【发布时间】:2017-01-16 22:22:16
【问题描述】:
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 / $distiller 是一个 mongo ObjectID。一个参考。

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

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

匹配按预期工作,但是当我包含组和计数时,我不断收到为 countedData 返回的空数组。

counted data : []

【问题讨论】:

    标签: mongodb mongoose aggregation-framework


    【解决方案1】:

    你聚合的group部分不正确,改成:

    .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 }
    }}
    

    我还移动了匹配,最好在第一个管道阶段进行匹配,以便使用集合中存在的索引。如果在管道中更进一步,则无法使用索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-25
      • 2020-09-22
      • 1970-01-01
      • 2018-07-12
      • 2017-08-03
      • 2020-03-21
      • 2013-04-25
      • 2019-03-27
      相关资源
      最近更新 更多