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

2019-01-06 19:25发布

问题:

I'm trying to query my database for prices greater than/less than a user specified number. In my databse, 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?

回答1:

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.



回答2:

$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 }


回答3:

Alternatively you can convert the values to Int, as per: http://www.quora.com/How-can-I-change-a-field-type-from-String-to-Integer-in-mongodb

var convert = function(document){
var intValue = parseInt(document.field, 10);
  db.collection.update(
    {_id:document._id}, 
    {$set: {field: intValue}}
  );
}

db.collection.find({field: {$type:2}},{field:1}).forEach(convert)


标签: mongodb