[英]How to do MongoDB query with JavaScript expression in Java code , like in Mongo shell
1. I know how to query with JavaScript expression in Mongo shell ( collection name is resource_phys
. field name is val
which defined as String type and contains only numeric value ) : 1.我知道如何在Mongo shell中使用JavaScript表达式进行查询 (集合名称为
resource_phys
。字段名称为val
,其定义为String类型,并且仅包含数字值 ):
//in Mongo shell:
var query1 = ("Number(this.val)>-1 && Number(this.val)<3")
db.resource_phys.find(query1)
//result found
2. Now, I want to do the same thing in Java code but cannot find any API to support JavaScript. 2.现在,我想用Java代码做同样的事情,但是找不到任何支持JavaScript的API。 I solicit your help to give some hints.
我恳请您提供一些提示。
3.Ps If the field val
is numeric type, I am aware of using operator $gt
and $lt
: 3.Ps如果字段
val
是数字类型,我知道使用运算符$gt
和$lt
:
//in Java codes:
DBCollection coll = db.getCollection("resource_phys");
DBObject query2 = new BasicDBObject("val",new BasicDBObject("$gt",-1).append("lt",3));
DBCursor cursor = coll.find(query2);
//result got in cursor
The form of query you are doing in the shell is actually just a shortcut form of the $where
operator. 您在shell中执行的查询形式实际上只是
$where
运算符的快捷方式。 So you would translate like this: 所以你会这样翻译:
DBObject query = new BasicDBObject(
"$where",
"Number(this.val)>-1 && Number(this.val)<3"
);
Please note the documentation though, as running JavaScript is not a good idea for performance. 但是请注意文档,因为运行JavaScript并不是提高性能的好主意。 You really should convert your strings to be actual numeric values.
您确实应该将字符串转换为实际的数值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.