猫鼬聚合错误:参数必须是聚合管道运算符

时间:2018-10-23 04:02:03

标签: node.js mongodb mongoose aggregation-framework

我已经按照我的要求编写了以下代码来汇总数据。当我尝试使用3t机器人时,此方法有效。下面的代码有什么问题。出现错误,因为“参数必须是聚合管道运算符”。

db.model('KeywordRanking').aggregate([
                {
                    $match: {
                        user: req.user._id
                    }
                },
                {
                    $project: {
                        "keyword": 1,
                        "user": 1,
                        "website": 1,
                        "rank": 1,
                        "type": 1,
                        "createdDateStr": 1
                    }
                },
                {
                    $lookup: {
                        from: "keywords",
                        localField: "keyword",
                        foreignField: "_id",
                        as: "keyword_refs"
                    }
                },
                { $unwind: "$keyword_refs" },
                {
                    $group: {
                        "_id": { "keyword": "$keyword", "website": "$website" },
                        "website": { "$first": "$website" },
                        "user": { "$first": "$user" },
                        "type": { "$first": "$type" },
                        "ranks": { "$push": { "createdDateStr": "$createdDateStr", "rank": "$rank" } },
                        "keyword_refs": { "$addToSet": "$keyword_refs" }
                    }
                },
                { $limit: count },
                { $skip: skip }
            ], { allowDiskUse: true });

1 个答案:

答案 0 :(得分:0)

mongoose aggregate仅接受管道数组和回调(如果需要promise,则省略回调)

对于allowDiskUSe,您可以按以下方式使用此聚合帮助器

    db.model('KeywordRanking').aggregate([
            {
                $match: {
                    user: req.user._id
                }
            },
            {
                $project: {
                    "keyword": 1,
                    "user": 1,
                    "website": 1,
                    "rank": 1,
                    "type": 1,
                    "createdDateStr": 1
                }
            },
            {
                $lookup: {
                    from: "keywords",
                    localField: "keyword",
                    foreignField: "_id",
                    as: "keyword_refs"
                }
            },
            { $unwind: "$keyword_refs" },
            {
                $group: {
                    "_id": { "keyword": "$keyword", "website": "$website" },
                    "website": { "$first": "$website" },
                    "user": { "$first": "$user" },
                    "type": { "$first": "$type" },
                    "ranks": { "$push": { "createdDateStr": "$createdDateStr", "rank": "$rank" } },
                    "keyword_refs": { "$addToSet": "$keyword_refs" }
                }
            },
            { $limit: count },
            { $skip: skip }
        ]).allowDiskUse(true);