MongoDB $gt/$lt operators with prices stored as strings

mongodb

Solution

If you intend to use $gt with strings, you will have to use regex, which is not great in terms of performance. It is easier to just create a new field which holds the number value of price or change this field type to int/double. A javascript version should also work, like so:

db.products.find("this.price > 30.00")

as js will convert it to number before use. However, indexes won't work on this query.

Problem

I'm trying to query my database for prices greater than/less than a user specified number. In my database, prices are stored like so: ``` {price: "300.00"} ``` According to the docs, this should work: ``` db.products.find({price: {$gt:30.00}}).pretty() ``` But I get no results returned. I've also tried `{price: {$gt:30}}`. What am I missing here? It it because the prices are stored as a string rather than a number in the DB? Is there a way around this?

Original source