Is there a way to do a less than or equal to query on a string field of a number?
Example Data
| Id | Price |
| 1 | "1000.00" |
| 2 | "5400.00" |
| 3 | "750.00" |
When I execute this query it returns all of the records:
db.MyCollection.find({ Price: {$lte: "1000.0"} })
When I execute this query it returns nothing:
db.MyCollection.find({ Price: {$lte: 1000.0} })
For comparison of different BSON type values, see the specified BSON comparison order. If the field holds an array, then the $in operator selects the documents whose field holds an array that contains at least one element that matches a value in the specified array (for example, <value1> , <value2> , and so on).
You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.
You can use this operator in methods like find(), update(), etc. according to your requirements. This operator performs short-circuit evaluation. If the first expression of $and operator evaluates to false, then MongoDB will not evaluate the remaining expressions in the array.
Update (valid from MongoDB v4.0 onwards):
You can use a combination of $expr and $toDouble to achieve the desired behaviour like this:
db.MyCollection.find({ $expr: { $lte: [ { $toDouble: "$Price" }, 1000.0 ] } })
Original Answer (MongoDB v3.6 and below):
MongoDB cannot convert strings to numbers. So your only option here is to use the dreaded $where operator:
db.MyCollection.find({ $where: "parseInt(this.Price) <= 1000" })
This won't use any indexes and is not exactly fast but perhaps kind of ok still for small collections.
Nonetheless I would recommend storing numbers as numerical types. So you should convert your string
s to int
s or long
s (or probably double
s even) as shown here: how to convert string to numerical values in mongodb
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With