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

Starting Mongo 4.0, there is a new $toDouble aggregation operator which converts from various types to double (in this case from a string):

// { price: "300.00" }
// { price: "4.2" }
 db.collection.find({ $expr: { $gt: [{ $toDouble: "$price" }, 30] } })
// { price: "300.00" }

$gt is an operator that can work on any type:

db.so.drop();
db.so.insert( { name: "Derick" } );
db.so.insert( { name: "Jayz" } );
db.so.find( { name: { $gt: "Fred" } } );

Returns:

{ "_id" : ObjectId("51ffbe6c16473d7b84172d58"), "name" : "Jayz" }

If you want to compare against a number with $gt or $lt, then the value in your document also needs to be a number. Types in MongoDB are strict and do not auto-convert like they f.e. would do in PHP. In order to solve your issue, make sure you store the prices as numbers (floats or ints):

db.so.drop();
db.so.insert( { price: 50.40 } );
db.so.insert( { price: 29.99 } );
db.so.find( { price: { $gt: 30 } } );

Returns:

{ "_id" : ObjectId("51ffbf2016473d7b84172d5b"), "price" : 50.4 }

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.

Tags:

Mongodb