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

nanospeck picture nanospeck · Feb 14, 2017 · Viewed 37.4k times · Source

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.

Answer

chridam picture chridam · Feb 14, 2017

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 }
        }           
    }
])