1

Using a java class i want to execute MongoDB shell query stored in a String variable.Currently i am using the following code.

String query="db.INSTANT.insert( { item: 'card', qty: 12 } )";
MongoClient mongo = new MongoClient("localhost",27017);
DB db = mongo.getDB("mydb");
db.eval(query);

The above code works fine for insert. But i want to execute find statement like query=db.INSTANT.find({"item":"card"}).Is there any way to execute this query and print the collection set.

1 Answer 1

1

Assuming that the function of eval has been deprecated since version 3.0.

The helper db.eval() in the Java Driver wraps the mongo eval command, So you can evaluate JavaScript code this way

String query="db.INSTANT.find( { item: 'card', qty: 12 } ).toArray()";
Sign up to request clarification or add additional context in comments.

5 Comments

I want to print the result set. Can you please demonstrate it with a sample code.
You can cast result as (List<BasicDBObject>) db.eval(query);
I typecasted like "List<BasicDBObject> ob =(List<BasicDBObject>) db.eval(query);" and I am getting this exception. "Exception in thread "main" java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to java.util.List at com.sixdee.demo.MongoQuery.main(MongoQuery.java:23)". What goes wrong in it.
Did you add the "toArray()"?
Thank you.It is working. Is there any another way to do this. My intention is to execute normal MongoDB query using a java class.

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.