Is it possible to cast in a MongoDB-Query?

2019-01-14 22:02发布

问题:

When I have two MongoDB documents like this...

db.test.insert( {"value" : "10123"} );
db.test.insert( {"value" : "160"} );

The result of a query like:

db.test.find({"value" :{$gt : "12"} });

is..

{ "_id" : ObjectId("4c6d1b92304326161b678b89"), "value" : "160" }

It's obvious, that a string comparison is made, so that my first value is not returned. Is there any way to cast within the query?

Something like:

db.test.find({ (int) "value" :{$gt : 12} });

would be great. A query like

db.test.find({"value" :{$gt : 12} }); // without the quotes around "12"

returns nothing.

回答1:

You can use the following JavaScript expression:

db.test.find("this.value > 12")

This uses JavaScript's automatic conversion from string to number.



回答2:

I have a similar workaround, i find that if you can use the mongo shell, you can write an statement to do this in javascript, but capable of using indexes.

var myItems = []
var it = db.test.find({},{value:1})
while (it.hasNext()){
 var item = it.next();
 if(parseInt(item.value) > 12)
  myItems.push(item);
}

If you want this to run faster than previus solution, you have to ensure the index on the value field.



回答3:

To convert String into int use this

db.test.find({'year': {$type: 2}}).forEach(
    function (x) {
        x.value=new NumberInt(x.value); 
        db.test.save(x)}
    )

And after that you can directly query like :

db.test.find({"value" :{$gt : 12} });


回答4:

$gt wasn't set for this use case. You would have to use regex for strings. Probably easier to just create a new field with the number as a number.