0

I am applying the query to get records which are LessthanOREqual to 9, Price in MongoDB stored as string.

So whenever I appy filter like this:

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

It will return records less than 9 as well as some with greater than 9.

Can anyone suggest what's wrong?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
Tejas
  • 296
  • 3
  • 12

1 Answers1

1

I don't think you should use $lte comparison operator to compare values in string datatype which is not accurate.

Instead, cast the price field to numeric datatype and then compare.

In MongoDB query command:

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

Sample Mongo Playground

With MongoDB Compass, you can export the query to specific language. And add the generated BsonDocument to filterDefinition.

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

Sample Data

Sample Data

Result

Result

Yong Shun
  • 35,286
  • 4
  • 24
  • 46