使用Java驱动程序从MongoDB获取结果的更好方法

时间:2016-07-25 13:12:52

标签: mongodb mongodb-java

我是MongoDB的新手。我使用MongoDB和Java-driver-3.2.2。之前我使用followong代码从数据库中获取结果。

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);

我的查询如下:

1)新的API(document.toJson())是否会比旧的depricated API(使用toString(DBCursor))提高性能? 2)我发现有3种方法可以使用新的API从mongoDB中获取结果,在所有3种方法中哪一种更好?

1 个答案:

答案 0 :(得分:1)

1)_ toJson和toString之间存在细微差别。 toJson将返回文档的JSON表示,而toString将提供默认的字符串输出。

如果您已实现自定义toString,那么性能取决于您对toString的实现。

如果使用默认的toString,那么与toString相比,toJson应该花费更多的时间。您可以通过对两者使用System.currentTimeMillis()来验证这一点。

2)_所有3种方式对于DB上的CRUD同样合法。现在,如果您考虑哪一个优先于另一个真正取决于您的应用程序以及您需要做什么。

如果您只想查看带有少量gt,lt等过滤器的快速查询,那么您应该选择第一种方法;列出查询的整个结果并显示它。简单易行。

另一方面,如果您想对检索到的结果执行某些任务,那么我建议采用第二种或第三种方法。请记住,FindIterable和MongoCursor之间存在轻微的使用差异。

MongoCursor是一个简单的迭代器,没有别的;而FindIterable允许您构建查询。以下引用可以深入了解FindIterable。

  

实际上,FindIterable类似于旧的DBCursor,就像一个   DBCursor是Iterable接口的一个实现。所以你可以   同样对待它来循环查询结果。关键的区别是   FindIterable是一个比DBCursor更高的抽象,它的a   可链接的界面,允许用户以流利的方式构建查询   通过更改过滤器和选项的方式。处于最高水平   FindIterable是MongoIterable接口的一个实现   表示一些MongoDB操作的结果,无论是查询还是   命令。   https://groups.google.com/forum/#!msg/mongodb-user/pcVX84PPwM0/FJ1EjPkAAz0J

因此,如果您只想查看一次查询结果,并且可能对每个查询执行一个简单的任务,那么您可以使用MongoCursor。

我个人坚持使用FindIterable,因为(简单的经验法则)它提供了其他方法所做的所有功能以及更多功能。