Saturday, March 29, 2014

MongoDB: Convert data getting from MongoDB into JSON Format

Today I am working on one of the use case in which I have to integrate MongoDB with Oracle SOA and expose a rest service from Oracle SOA which output the response as a JSON String. As Oracle does not provide any out of box functionality or adapters to connect with mongoDB,  so I am using the mongodb java drivers library to access the Mongo database in SOA using Java embedding activity.
In general we use the json data to interact with mongo db and I am using the same in Oracle SOA to interact with mongo db.

This blog post is about the problem faced by many developers to convert the data getting from mongo db to JSON String. Now query for getting the whole data for particular collection is :
DBCursor cursor = collection.find();
here collection is a object of class com.mongodb.DBCollection and cursor is an object of class 
com.mongodb.DBCursor
Now one way to iterate over all the data is to use following:

DBCursor cursor = collection.find( query );
 if( cursor.hasNext() )
 DBObject obj = cursor.next();

or another way is to convert cursor object into the json string using serialize method of  com.mongodb.util.JSON class and return back this json string as a response.

Please find below the example to convert DBCursor into JSON String.


package poc.nile.test;

import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;

import java.net.UnknownHostException;

public class DBTest {
    public static void main(String arg[]){
       
         MongoClient mongoClient;
         String host= "localhost";
         int port=27017;
         String dbName="test";
        try {
           mongoClient = new MongoClient(host,port);
           DBCollection collection = mongoClient.getDB(dbName).getCollection("products");
          DBCursor cursor = collection.find();
         JSON json =new JSON();
        String serialize = json.serialize(cursor);
        System.out.println(serialize);
       } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
        }
    }
     
}

No comments:

Post a Comment