Search code examples
javamongodbjacksonmongo-javamongo-jackson-mapper

Execute mongoDB shell like query using a java class


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.


Solution

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