Mongodb - bad query: BadValue unknown top level op

2019-04-05 16:14发布

问题:

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"
        }

回答1:

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.