Execute mongoDB shell like query using a java class

1.9k Views Asked by At

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

There are 1 best solutions below

5
On BEST ANSWER

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()";