Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is FindIterable<Document> load all documents?

Tags:

java

mongodb

Currently, I'm using MongoCollection<Document> to get all documents, the return type is FindIterable<Document>, then loop over Iterable to process each document.

Ex:

FindIterable<Document> docs = getCollection().find();
for(Document doc : docs) {
    ...
}

But I don't know whether FindIterable will load all documents and loop it or it's just loads the cursor and fetch the documents later when looping?

like image 339
Quan Vo Avatar asked Jan 25 '26 05:01

Quan Vo


1 Answers

What you are asking for is an implementation detail of the Mongo Java Driver, and thus not part of the public interface and thus not guaranteed to stay the same in future versions.

This disclaimer aside, as of 3.2.x, the find() call creates a FindOperationIterable under the hood, which uses a MongoBatchCursorAdapter as its iterator, which in turn is based on a BatchCursor.

The javadoc in the batch cursor states:

"MongoDB returns query results as batches, and this interface provideds an iterator over those batches. The first call to the next method will return the first batch, and subsequent calls will trigger a request to get the next batch of results. Clients can control the batch size by setting the batchSize property between calls to next."

Thus, it will read results in batches, and query the database again, if the current batch has been read completely.

like image 134
mtj Avatar answered Jan 26 '26 19:01

mtj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!