About MongoDB Java driver: collection.find().iterator();

60 views
Skip to first unread message

Andy Fan

unread,
Jan 26, 2018, 5:05:09 PM1/26/18
to mongodb-user
I read the document  http://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/#find-all-documents-in-a-collection

and the suggested way is 

MongoCursor<Document> cursor = collection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); }

now my questions are:
=
1. is it possbile that the `collection.find().iterator()` create the cursor on server side but client get SOCKET_TIMEOUT before the return of collection.find().iterator() return, so cursor.close failed?
if I change to 'if (cursor != null), it still have cursor leak since cursor is null?
2. will `collection.find().iterator()` to get the real data for the first batch before return?

Anthony Maire

unread,
Jan 29, 2018, 5:02:03 AM1/29/18
to mongodb-user
Hi Andy

I think the cleaner way to do that is to use the "try-with-ressource" statement since MongoCursor extends Closeable. It handles the possible null check automagically and avoid some issues in more complex code when you may have several things to do in your finally block (and some of them are before the call to cursor.close(), leading to cursor leak if a runtime exception is thrown )

try (MongoCursor<Document> cursor = collection.find().iterator()) {
        while (cursor.hasNext()) {
System.out.println(cursor.next().toJson()); }
}
Reply all
Reply to author
Forward
0 new messages