Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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:

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.

like image 989
nanospeck Avatar asked Feb 14 '17 17:02

nanospeck


1 Answers

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

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 $sum within the $group pipeline as:

    { 
        "$group": {
            "_id": {
                "year": { "$year": "$tweettime" },
                "dayOfYear": { "$dayOfYear": "$tweettime" },
                "interval": {
                    "$subtract": [ 
                        { "$minute": "$tweettime" },
                        { "$mod": [{ "$minute": "$tweettime"}, 15] }
                    ]
                }
            },
            "count": { "$sum": 1 }
        }           
    }
])
like image 175
chridam Avatar answered Nov 11 '22 17:11

chridam