Access Data From a Cursor
On this page
Overview
In this guide, you can learn how to access data using a cursor with the MongoDB Java driver.
A cursor is a mechanism that allows an application to iterate over database results while only holding a subset of them in memory at a given time. The driver uses cursors in read operations that match multiple documents to return matched documents in batches as opposed to returning them all at once.
This page uses an initiating method, find()
to show how to access
data from a FindIterable.
Note
The following ways to access and store data apply to other iterables such as an AggregateIterable.
The find()
method creates and returns an instance of a
FindIterable
. A FindIterable
allows you to browse the documents
matched by your search criteria and to further specify which documents
to see by setting parameters through methods.
Terminal Methods
Terminal methods execute an operation on the MongoDB deployment after
configuring all parameters of an Iterable
instance controlling the
operation.
First
Use the first()
method to retrieve the first document in your query
results:
FindIterable<Document> iterable = collection.find(); System.out.println(iterable.first());
This method is often used when your query filter will match one document, such as when filtering by a unique index.
Number of Results
Use the available()
method to retrieve the number of results
locally present without blocking:
MongoCursor<Document> cursor = collection.find().cursor(); System.out.println(cursor.available());
The method returns 0
if the application has already iterated through
all the documents in the cursor or if the cursor is closed.
Into
Use the into()
method to store your query results in a List
:
List<Document> results = new ArrayList<>(); FindIterable<Document> iterable = collection.find(); iterable.into(results); System.out.println(results);
This method is often used when your query filter returns a small number of documents that can fit into available memory.
Cursor
Use the cursor()
method to iterate through fetched documents and
ensure that the cursor closes if there is an early termination:
MongoCursor<Document> cursor = collection.find().cursor();
For more information about how to ensure a cursor closes, see the cursor cleanup section.
Explain
Use the explain()
method to view information about how MongoDB
executes your operation.
The explain()
method returns execution plans and performance
statistics. An execution plan is a potential way MongoDB
can complete an operation. The explain()
method provides both the
winning plan (the plan MongoDB executed) and rejected plans.
You can specify the level of detail of your explanation by passing a
verbosity level to the explain()
method.
The following table shows all verbosity levels for explanations and their intended use cases:
Verbosity Level | Use Case |
---|---|
ALL_PLANS_EXECUTIONS | You want to know which plan MongoDB will choose to run your query. |
EXECUTION_STATS | You want to know if your query is performing well. |
QUERY_PLANNER | You have a problem with your query and you want as much information as possible to diagnose the issue. |
The following example prints the JSON representation of the winning plan for aggregation stages that produce execution plans:
Document explanation = collection.find().explain(ExplainVerbosity.EXECUTION_STATS); List<String> keys = Arrays.asList("queryPlanner", "winningPlan"); System.out.println(explanation.getEmbedded(keys, Document.class).toJson());
The preceding code snippet produces the following output:
{ "stage": "COLLSCAN", "direction": "forward" }
For more information about the explain operation, see the following Server Manual Entries:
For more information about the methods and classes mentioned in this section, see the following API Documentation:
Usage Patterns
A MongoCursor
and FindIterable
allow you to access query results
one document at a time, abstracting away network and caching logic.
Functional Iteration
Pass a function to the forEach()
method of a FindIterable
to
iterate through results in a functional style:
FindIterable<Document> iterable = collection.find(); iterable.forEach(doc -> System.out.println(doc.toJson()));
Important
Initiating methods return objects that implement the Iterable
interface which allows you
to iterate through them using iterator methods. Sometimes, we use an enhanced
for-each loop to iterate through results:
for (Document cursor : collection.find()) { ... }
Iterating this way is not preferable because if an exception is
thrown before the loop completes, the cursor will not close. Using a
MongoCursor
allows us to ensure the cursor closes as shown in the
cursor cleanup section.
Conditional Iteration
Use the hasNext()
method to check if there are any documents
available in the cursor, and then use the next()
method to retrieve
the next available document from the cursor:
MongoCursor<Document> cursor = collection.find().cursor(); while (cursor.hasNext()){ System.out.println(cursor.next().toJson()); }
For more information about the methods and classes mentioned in this section, see the following API Documentation:
Cursor Cleanup
Close
Use the close()
method in a finally
block to free up a cursor's
consumption of resources in both the client application and the MongoDB
deployment:
MongoCursor<Document> cursor = collection.find().cursor(); try { while (cursor.hasNext()){ System.out.println(cursor.next().toJson()); } } finally { cursor.close(); }
Try with Resources Statement
Use a try-with-resources statement to automatically free up a cursor's consumption of resources in both the client application and the MongoDB deployment:
try(MongoCursor<Document> cursor = collection.find().cursor()) { while (cursor.hasNext()){ System.out.println(cursor.next().toJson()); } }
For more information about the methods and classes mentioned in this section, see the following API Documentation: