MongoDB 聚合错误:管道阶段规范对象必须恰好包含一个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42232375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:54:38  来源:igfitidea点击:

MongoDB Aggregation error : Pipeline stage specification object must contain exactly one field

mongodbmongodb-queryaggregation-framework

提问by nanospeck

I am new to mongodb and trying out aggregation for first time. Here, I am trying to get the count of tweets grouped by every 15 minutes. When I try to run the below query in mongo console I get the error:

我是 mongodb 的新手,第一次尝试聚合。在这里,我试图获取每 15 分钟分组的推文计数。当我尝试在 mongo 控制台中运行以下查询时,出现错误:

A pipeline stage specification object must contain exactly one field.

管道阶段规范对象必须恰好包含一个字段。

    db.hashtag.aggregate([
    { "$group": {
        "_id": {
            "year": { "$year": "$tweettime" },
            "dayOfYear": { "$dayOfYear": "$tweettime" },
            "interval": {
                "$subtract": [ 
                    { "$minute": "$tweettime" },
                    { "$mod": [{ "$minute": "$tweettime"}, 15] }
                ]
            }
        }},
        "count": { "$sum": 1 }
    }
])

I couldn't find a good explanation of the reason in SO. Kindly share your thoughts on this subject and why my the query has an error.

我在 SO 中找不到对原因的很好解释。请分享您对这个主题的想法以及为什么我的查询有错误。

回答by chridam

MongoDB is complaining because you have an unrecognised pipeline stage specification "count": { "$sum": 1 }in your pipeline.

MongoDB 抱怨是因为您的管道中有一个无法识别的管道阶段规范"count": { "$sum": 1 }

Your original pipeline when formatted properly

正确格式化后的原始管道

db.hashtag.aggregate([
    { 
        "$group": {
            "_id": {
                "year": { "$year": "$tweettime" },
                "dayOfYear": { "$dayOfYear": "$tweettime" },
                "interval": {
                    "$subtract": [ 
                        { "$minute": "$tweettime" },
                        { "$mod": [{ "$minute": "$tweettime"}, 15] }
                    ]
                }
            }
        },
        "count": { "$sum": 1 } /* unrecognised pipeline specification here */
    }
])

should have the aggregate accumulator $sumwithin the $grouppipeline as:

管道$sum内的聚合累加器应$group为:

    { 
        "$group": {
            "_id": {
                "year": { "$year": "$tweettime" },
                "dayOfYear": { "$dayOfYear": "$tweettime" },
                "interval": {
                    "$subtract": [ 
                        { "$minute": "$tweettime" },
                        { "$mod": [{ "$minute": "$tweettime"}, 15] }
                    ]
                }
            },
            "count": { "$sum": 1 }
        }           
    }
])