0

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 ) :

//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. I solicit your help to give some hints.

3.P.s. If the field val is numeric type, I am aware of using operator $gt and $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

1 Answer 1

1

The form of query you are doing in the shell is actually just a shortcut form of the $where operator. 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. You really should convert your strings to be actual numeric values.

Sign up to request clarification or add additional context in comments.

1 Comment

Amazing! Awesome!Fabulous!Thanks! ---I did tried using $where but not worked, but now your code works fine.so strange! And I did know the performance issue but just leave it right now...Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.