8

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} })
ferensilver
  • 341
  • 2
  • 4
  • 17

1 Answers1

13

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 strings to ints or longs (or probably doubles even) as shown here: how to convert string to numerical values in mongodb

dnickless
  • 10,733
  • 1
  • 19
  • 34
  • 7
    I find this frustrating. Isn't the point of using MongoDB that you can have a flexible schema (one day you're storing strings, the next day numbers, and they all work). Now, it seems, I need to go back and convert all these string number values into numbers. – Joao May 31 '18 at 17:03
  • 2
    @Joao, cannot agree more with you. – EugenSunic Feb 08 '19 at 22:07