Mongodb - bad query: BadValue unknown top level operator: $gte

Evaldas Raisutis picture Evaldas Raisutis · Nov 5, 2014 · Viewed 53.9k times · Source

What is wrong with this query? I tried to run it on mongodb server and received an error as following - "exception: bad query: BadValue unknown top level operator: $gte". Can anyone tell me what is wrong with it, please?

        db.scores.aggregate([ 
            { 
                $match: { 
                    $or: [ 
                        { $gte: [ "$score", 30 ] }, 
                        { $lte: [ "$score", 60 ] } 
                    ] 
                } 
            },
            { 
                $group: { 
                    _id: "$gamer",
                    games: { $sum: 1 }
                } 
            }
        ])

sample data :

        {
            "_id" : "545665cef9c60c133d2bce72",
            "score" : 85,
            "gamer" : "Latern"
        }

        /* 1 */
        {
            "_id" : "545665cef9c60c133d2bce73",
            "score" : 10,
            "gamer" : "BADA55"
        }

        /* 2 */
        {
            "_id" : "545665cef9c60c133d2bce74",
            "score" : 62,
            "gamer" : "BADA55"
        }

        /* 3 */
        {
            "_id" : "545665cef9c60c133d2bce75",
            "score" : 78,
            "gamer" : "l00ser"
        }

        /* 4 */
        {
            "_id" : "545665cef9c60c133d2bce76",
            "score" : 4,
            "gamer" : "l00ser"
        }

        /* 5 */
        {
            "_id" : "545665cef9c60c133d2bce77",
            "score" : 55,
            "gamer" : "FunnyCat"
        }

Answer

Neil Lunn picture Neil Lunn · Nov 5, 2014

You did this wrong. Should be:

db.scores.aggregate([
    { "$match": {
        "score": { "$gte": 30, "$lte": 60 }
    }},
    { "$group": {
        "_id": "$gamer",
        "games": { "$sum": 1 }
    }}
])

Which is the proper way to specify a "range" query where the actual conditions are "and" and therefore "between" the operands specified.