Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo Cast String to Number for Query

Tags:

mongodb

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} })
like image 461
ferensilver Avatar asked Dec 20 '17 23:12

ferensilver


People also ask

How do I use $in in MongoDB?

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).

How fetch data from MongoDB?

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.

What is the purpose of Find () method in MongoDB?

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.

Can we use $and in find in MongoDB?

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.


1 Answers

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

like image 51
dnickless Avatar answered Sep 21 '22 09:09

dnickless