Search code examples
mongodbspring-data-mongodbmongodb-javamongodb-java-3.3.0

Difference between MongoCursor<Document> vs FindIterable<Document>


I want know what is the difference between MongoCursor and FindIterable.

MongoCursor:

MongoCursor<Document> cursorPersonDoc = personDocCollection.find(whereClauseCondition).iterator();
        while (cursorPersonDoc.hasNext()) {
           Document doc = cursorPersonDoc.next();
           String s1 = doc.getString("s1");
         }

FindIterable:

FindIterable<Document> cursorPersonDoc = personDocCollection.find(whereClauseCondition);
    for (doc: cursorPersonDoc){
      String s1 = doc.getString("s1");
    }

Solution

  • If you look at the methods which are there in both the classes you will get an idea.

    FindIterable has methods like filter, limit, skip which will help you in filtering out the results.
    And also it has methods like maxAwaitTime(for tailable cursors) and maxTime.

    MongoCursor doesn't have all these. But there is one advantage using MongoCursor. MongoCursor interface extends Closeable, which in turn extends AutoCloseable.

    AutoCloseable (introduced in Java 7) makes it possible to use try-with-resources idiom. Something like this

    try (final MongoCursor cursor = personDocCollection.find(whereClauseCondition).iterator()) {
       ........
     }