Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.*;
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.

like image 843
aditya_gaur Avatar asked Feb 01 '11 09:02

aditya_gaur


People also ask

Can I connect MongoDB with Java?

Connecting via Java. Assuming you've resolved your dependencies and you've set up your project, you're ready to connect to MongoDB from your Java application. Since MongoDB is a document database, you might not be surprised to learn that you don't connect to it via traditional SQL/relational DB methods like JDBC.

Can we write queries in MongoDB?

The $in operator allows you to write queries that will return documents with values matching one of multiple values held in an array. The following example query includes the $in operator, and will return documents whose name value matches either Everest or K2 : db.

Which method is used to query data from MongoDB collection?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.


3 Answers

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.

like image 169
AlikElzin-kilaka Avatar answered Oct 08 '22 08:10

AlikElzin-kilaka


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: http://www.mongodb.org/display/DOCS/Data+Types+and+Conventions

UPD: Scott Hernandez pointed out about JSON.parse.

like image 30
pingw33n Avatar answered Oct 08 '22 06:10

pingw33n


Take a look at the Jongo library - it will allow you to run even pretty advanced queries using the command-line syntax.

It also uses a very fast GSON mapper to return your own objects back to you as the result of the query, instead of a list of BasicDBObjects.

like image 2
Ryan Kimber Avatar answered Oct 08 '22 06:10

Ryan Kimber