MongoDB 聚合 $match 错误: "参数必须是聚合管道操作符"

28

我可以使用聚合获取网站的所有统计信息,但我想为特定用户执行此操作,例如$where

所有统计信息:

games.aggregate([{
                $group: {
                    _id: '$id',
                    game_total: { $sum: '$game_amount'}, 
                    game_total_profit: { $sum: '$game_profit'}}
                }]).exec(function ( e, d ) {

                    console.log( d )            

            })

当我尝试使用$match运算符时,我遇到了错误:

games.aggregate([{
                $match: { '$game_user_id' : '12345789' },
                $group: {
                    _id: '$id',
                    game_total: { $sum: '$game_amount'}, 
                    game_total_profit: { $sum: '$game_profit'}}
                }]).exec(function ( e, d ) {

                    console.log( d )            

            })

Arguments must be aggregate pipeline operators

我漏掉了什么?

4个回答

45

管道阶段是数组中独立的BSON文档:

games.aggregate([
                { $match: { 'game_user_id' : '12345789' } },
                { $group: {
                    _id: '$id',
                    game_total: { $sum: '$game_amount'}, 
                    game_total_profit: { $sum: '$game_profit'}}
                }}
]).exec(function ( e, d ) {
    console.log( d )            
});

在JavaScript中,数组或[]方括号表示法意味着它需要提供一个“列表”。这意味着需要提供一组“文档”,通常使用JSON符号{}大括号来指定。


谢谢你。但是当我查询用户时,我只得到了 []。(当我删除 $match 的内容时,它可以工作(提供所有统计信息)。) - Lazy
2
我刚刚从 $game_user_id 中删除了 $ 符号,然后程序就奇迹般地正常工作了。但是我永远也不会理解 MongoDB...不管怎样,还是谢谢你的帮助。 - Lazy

4

可能的另一个原因是由于管道中的空对象 {}。如果在管道中使用了任何条件阶段,这种情况可能会发生。

例如:

const pipeline = []:
.....
.....
let sort = {}
if(params.sort){
 sort = { $sort: { popularity: -1 } }
}

pipeline.push(sort)

这会导致相同的错误 "Arguments must be aggregate pipeline operators"

相反,您可以使用类似以下方式:

let sort;
if(params.sort){
 sort = { $sort: { popularity: -1 } }
}
    
pipeline.concat(sort? [sort] : [])

3
 const stats = await Tour.aggregate([
 
    {
        $match: { ratingsAvarage: { $gte: 4.5 } }
    }, 
    {    
        $group: { 
        _id: null,
        avgRating: { $avg: '$ratingsAvarage' }
                   
         }
    }]

确保使用$obj或{}在数组内分隔流水线阶段。所以$match和$group必须放在一个对象中。


0

这可能是由于使用的mongodb版本和mongoose版本不兼容造成的另一个可能原因。

在我的情况下

mongodb版本: MongoDB shell版本v3.6.18

mongoose版本: "mongoose": "^5.1.3",

请查找兼容版本列表

https://mongoosejs.com/docs/compatibility.html


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接