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.

Nandu
  • 151
  • 1
  • 2
  • 12

1 Answers1

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()";
Marco
  • 741
  • 3
  • 18
  • I want to print the result set. Can you please demonstrate it with a sample code. – Nandu Dec 21 '18 at 10:30
  • You can cast result as (List) db.eval(query); – Marco Dec 21 '18 at 10:36
  • I typecasted like "List ob =(List) 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. – Nandu Dec 21 '18 at 11:07
  • Did you add the "toArray()"? – Marco Dec 21 '18 at 11:22
  • 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. – Nandu Dec 21 '18 at 12:58