Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"
        }
like image 283
Evaldas Raisutis Avatar asked Nov 05 '14 10:11

Evaldas Raisutis


2 Answers

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.

like image 161
Neil Lunn Avatar answered Nov 19 '22 11:11

Neil Lunn


Since MongoDB version 3.6, you may use $expr to use aggregate expressions within a query. So the query can be rewritten into:

db.scores.aggregate([
  {
    $match: {
      $expr: {
        $or: [
          { $gte: ["$score", 30] },
          { $lte: ["$score", 60] }
        ]
      }
    }
  },
  {
    $group: {
      _id: "$gamer",
      games: { $sum: 1 }
    }
  }
]);
like image 41
socrates Avatar answered Nov 19 '22 10:11

socrates