Filter.Lte(x=>x.Price, "9") 得到错误的结果

Filter.Lte(x=>x.Price, "9") getting wrong results

我正在应用查询来获取 LessthanOREqual 到 9 的记录,MongoDB 中的价格存储为字符串。

所以每当我像这样应用过滤器时:

filterDefinition&= Builders<DM.Content>.Filter.Lte(x => x.Price, "9");

它会 return 记录小于 9 以及一些大于 9 的记录。

谁能告诉我哪里出了问题?

我认为您不应该使用 $lte 比较运算符来比较不准确的字符串数据类型中的值。

相反,将 price 字段转换为数字数据类型,然后进行比较。

在MongoDB中查询命令:

{ $expr: { $lte: [ { $toInt: "$price" }, 9 ] } }

Sample Mongo Playground

使用 MongoDB 指南针,您可以 export the query to specific language。并将生成的BsonDocument添加到filterDefinition.

filterDefinition &= new BsonDocument("$expr", 
    new BsonDocument("$lte", 
        new BsonArray
        {
            new BsonDocument("$toInt", "$price"),
            9
        }));

Sample Data

Result