M.S.Naidu
M.S.Naidu

Reputation: 2289

Better way of fetching the result from the MongoDB using Java-driver

I am new to MongoDB. I am using MongoDB with Java-driver-3.2.2. Earlier I was using the followong code to fetch the result from the database.

MongoClient mongoClient = new MongoClient("localhost", 27017);
@SuppressWarnings("deprecation")
DB deviceBaseDB = mongoClient.getDB("test");
DBCollection deviceBaseCollection = deviceBaseDB.getCollection("myFirstCollection");

List<String> list = new ArrayList<String>();

        DBCursor cursor = deviceBaseCollection.find(queryObject, projection)
                .sort(sortingCriteriea).limit(10);

        while (cursor.hasNext()) {
            list.add(cursor.next().toString());
        }



But in the above code mongoClient.getDB() call is depricated. So I am trying to use New API() from MongoDB like below.


MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> collection = database.getCollection("myFirstCollection");


          // First approach
          List<Document> listDocs = collection.find().projection(projection)
              .sort(new BasicDBObject("likes", -1)).into(new ArrayList<Document>());  

      List<String> strList1 = new ArrayList<String>();

      for(Document doc : listDocs) {       
          strList1.add(doc.toJson());
      }
         System.out.println("List of json files  strList1:: " + strList1);


          // Second Approach   

          FindIterable<Document> iterableDocsWithFilter_SortWithProject = collection.find(
              new BasicDBObject("title", "New MongoDB Learning")).projection(projection)
              .sort(new BasicDBObject("likes", -1));  
      Iterator<Document> iterator = iterableDocsWithFilter_SortWithProject.iterator();

      List<String> strList2 = new ArrayList<String>();
      while (iterator.hasNext()) {
          strList2.add(iterator.next().toJson());
    }


     System.out.println("List of json files  strList2:: " + strList2);


         // Third Approach 

     MongoCursor<Document> mongoCursor = (MongoCursor<Document>) collection.find(
              new BasicDBObject("title", "New MongoDB Learning")).projection(projection)
              .sort(new BasicDBObject("likes", -1));

     List<String> strList3 = new ArrayList<String>();
     while(mongoCursor.hasNext()) {
         strList3.add(mongoCursor.next().toJson());
     }

         System.out.println("List of json files  strList3:: " + strList3);

My queries are below:

1) Will new API(document.toJson()) increase the performance as compare old depricated API (using toString(DBCursor)) ? 2) I found 3 ways to fetch the result from the mongoDB with new API, which one is better among all the 3 approaches?

Upvotes: 2

Views: 1524

Answers (1)

Newton
Newton

Reputation: 428

1)_ there is a slight difference between what toJson and toString do. a toJson will return a JSON representation of the document, whereas the toString will give the default string output.

If you have implemented a custom toString then the performance depends on your implementation of toString.

If you are using the default toString then toJson should take more time as compared to a toString. You can verify this by using System.currentTimeMillis() for both.

2)_ All 3 ways are equally legit for CRUD on the DB. Now if you think about which to prefer over the other that really depends on your application and what you need to do.

If you only want to check a quick query with a few gt, lt etc filters then you should go for the first approach; you list the whole result of the query and display it. Simple and easy.

On the other hand if you want to perform some tasks on the retrieved results then I would recommend to go with either the second or third approach. Kindly remember that there is a slight use difference between FindIterable and MongoCursor.

MongoCursor is a simple iterator, nothing else; while FindIterable lets you build queries . The below quote can put some insight into FindIterable.

In reality FindIterable is similar to the DBCursor of old and like a DBCursor its an implementation of the Iterable interface. So you can treat it similarly for looping query results. The key difference is that the FindIterable is a higher abstraction than a DBCursor, its a chainable interface that allows users to build up queries in a fluent way by changing filters and options. At its highest level FindIterable is an implementation of the MongoIterable interface which represents the results of some MongoDB operation be it a query or a command. https://groups.google.com/forum/#!msg/mongodb-user/pcVX84PPwM0/FJ1EjPkAAz0J

So if you just want to go through your query results once and maybe perform a simple task on each them you can resort to MongoCursor.

I personally stick with FindIterable because (simple rule of thumb) it offers all what the other methods do plus more.

Upvotes: 1

Related Questions