2014-11-05 42 views
6

此查询有什么问题?我试图在mongodb服务器上运行它,并收到如下错误 - “异常:错误的查询:BadValue未知顶级运算符:$ gte”。有谁能告诉我它有什么问题吗?

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

样本数据:

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

回答

8

你这样做是错误的。应该是:

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

这是指定一个“范围”的查询,其中实际情况是“和”,因此指定的操作数“之间”的正确方法。

+2

关键的一点是['$ match'采用查询语法](https://docs.mongodb.org/manual/reference/operator/aggregation/match/),所以你想使用[query'$ gte'运营商](https://docs.mongodb.org/manual/reference/operator/query/gte/)而不是[聚合'$ gte'运营商](https://docs.mongodb.org/manual/参考/运营商/聚集/ GTE /)。 (顺便说一下,[范围查询](https://docs.mongodb.org/manual/reference/method/db.collection.find/#query-for-ranges)通过使用[隐式'$和']( https://docs.mongodb.org/manual/reference/operator/query/and/)。) – duozmo 2016-02-15 18:34:08