Executing Mongo like Query (JSON)through Java

aditya_gaur picture aditya_gaur · Feb 1, 2011 · Viewed 31.6k times · Source

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.*;
import java.net.UnknownHostException;
public class ExecuteQuery {
public static void main(String args[]){
    try{
          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){
          System.out.println(e);
       }
       catch (MongoException.DuplicateKey e) {
          System.out.println("Exception Caught" + e);
       }
}
}

Note: executeQuery() 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 BasicDBObject instance? Thanks.

Answer

AlikElzin-kilaka picture AlikElzin-kilaka · Sep 15, 2016

Yes, there is way, by passing the filter as a string. Example:

BasicDBObject query = BasicDBObject.parse("{userId: {$gt: \"1\"}}");
FindIterable<Document> dumps = crapCollection.find(query);

You can Also use com.mongodb.util.JSON, but I don't recommend it. It's less descriptive.

DBObject dbObject = (DBObject)JSON.parse("{userId: {$gt: \"1\"}}");

Please notice that this might be vulnerable to SQL injections because you parse/build the filter yourself.

I recommend using Jongo's parameterized query.