简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM