aditya_gaur aditya_gaur - 1 month ago 10x
JSON Question

Executing Mongo like Query (JSON)through Java

I was wondering if there is a way to execute mongo like query directly through Java i.e. we give mongoDB like query as a String to a function in Java driver for mongoDB as a String Object and an DBCursor Object is returned. Something like:

import com.mongodb.*;
public class ExecuteQuery {
public static void main(String args[]){
Mongo m = new Mongo();
DB db = m.getDB("test");
DBCollection coll = db.getCollection("first");
DBObject doc = new BasicDBObject();
DBCursor cur =coll.executeQuery("db.first.find({"username":"joe"})");
catch(UnknownHostException e){
catch (MongoException.DuplicateKey e) {
System.out.println("Exception Caught" + e);

is not a built in function. It is just used for demonstration purposes.
So, Is there a function in the java api which converts a json string to a
instance? Thanks.


What you showed here is not JSON, it's Javascript code for embedded MongoDB Shell. If you need for some reason to execute the code inside Java environment you will have to embed Javascript engine (like Rhino) and implement compatible API.

Otherwise you just need to convert JSON to DBObject and you can do this with JSON.parse() method or any other JSON-mapping library like Jackson. Note that MongoDB uses extended set of data types that are not present in JSON:

UPD: Scott Hernandez pointed out about JSON.parse.