猫鼬聚合返回空结果 [英] Mongoose aggregate returning empty result

查看:48
本文介绍了猫鼬聚合返回空结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在处理猫鼬聚合请求时遇到问题.

I have problems with a mongoose aggregate request.

这有点让我发疯,因为我在任何地方都找不到解决方案.如有任何支持,我将不胜感激.

It's kind of driving me crazy cause I can't find a solution anywhere. I would be very grateful for any support.

架构:

var EvalSchema = new Schema({
    modified: {type: Date, default: Date.now},
    created : {type: Date, default: Date.now},
    username: {type: String, required: true},
    item: {type: String, required: true},
    criteria: [{
        description: {
            type: String
        },
        eval: {
            type: Number
        }
    }]
});
mongoose.model('Eval', EvalSchema);

并且我正在使用聚合来计算给定项目的每个标准的评估总和.

and I'm using an aggregation to compute the sum of evaluations for each criterion for a given item.

Eval.aggregate([{
    $match: {
        item: item.id
    }
}, {
    $unwind: "$criteria"
}, {
    $group: {
        _id: "$criteria.description",
        total: {
            $sum: "$criteria.eval"
        },
        count: {
            $sum: 1
        }
    }
}, {
    $project: {
        total: 1,
        count: 1,
        value: {
            $divide: ["$total", "$count"]
        }
    }
}], function(err, result) {
    if (err) {
        console.log(err);
    }
    console.log(result);
});

结果总是空的....

我正在记录应用程序中猫鼬触发的所有查询.当我在 Mongodb 中运行查询时,它返回正确的结果.

I'm logging all queries that mongoose fire in the application. When I run the query in Mongodb, it returns the correct result.

coll.aggregate([{
    '$match': {
        item: 'kkkkkkkkkkk'
    }
}, {
    '$unwind': '$criteria'
}, {
    '$group': {
        _id: '$criteria.description',
        total: {
            '$sum': '$criteria.eval'
        },
        count: {
            '$sum': 1
        }
    }
}, {
    '$project': {
        total: 1,
        count: 1,
        value: {
            '$divide': ['$total', '$count']
        }
    }
}])

结果:

{
    result: [{
        "_id": "Overall satisfaction",
        "total": 4,
        "count": 1,
        "value": 4
    }, {
        "_id": "service",
        "total": 3,
        "count": 1,
        "value": 3
    }, {
        "_id": "Quality",
        "total": 2,
        "count": 1,
        "value": 2
    }, {
        "_id": "Price",
        "total": 1,
        "count": 1,
        "value": 1
    }],
    ok: 1
}

模型引用了正确的集合.

The model is referencing the correct collection.

谢谢:)

推荐答案

你在 $match 函数中的 item.id 是一个字符串,因此你需要转换将其转换为 ObjectID,如下所示:

Your item.id in the $match function is a String, therefore you will need to convert it to an ObjectID, like so:

$match: { item: mongoose.Types.ObjectId(item.id) }

您可以在 GitHub aggregate 上参考此问题了解更多详情.

You can refer to this issue on GitHub aggregate for more details.

这篇关于猫鼬聚合返回空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆