Mongodb - 错误查询:BadValue未知顶级运算符:$ gte

时间:2014-11-05 10:52:10

标签: javascript mongodb mongodb-query aggregation-framework

此查询有什么问题?我试图在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"
        }

4 个答案:

答案 0 :(得分:11)

你做错了。应该是:

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

指定"范围"的正确方法是什么?查询实际情况是"和"因此"在"之间指定的操作数。

答案 1 :(得分:2)

从MongoDB 3.6版开始,您可以使用$expr在查询中使用聚合表达式。因此查询可以重写为:

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

答案 2 :(得分:0)

这可能对我这样的人有所帮助...在我的情况下,field 为空。并遇到此错误未知顶级运算符: $in , MongoDb Exception

private <T> void addQueryCondition (Query query, String field , List<T> valuesList ) {
    if (!CollectionUtils.isEmpty(valuesList)) {
        query.addCriteria(Criteria.where(field).in(valuesList).exists(true));
    }
}

答案 3 :(得分:-1)

您需要在cmd提示符中明确包含软件包,例如 npm i regex并按如下所示更改服务:

const kidDetails = await this.studentModel.find({ name:{$regex: new RegExp('.*' + studName, 'i') }} );