Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversJava

Access Data From a Cursor

On this page

  • Overview
  • Terminal Methods
  • First
  • Into
  • Cursor
  • Explain
  • Usage Patterns
  • Functional Iteration
  • Conditional Iteration
  • Cursor Cleanup
  • Close
  • Try with Resources Statement

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 execute an operation on the MongoDB deployment after configuring all parameters of an Iterable instance controlling the operation.

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.

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.

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 on how to ensure a cursor closes, see the cursor cleanup section.

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 should produce the following output:

{ "stage": "COLLSCAN", "direction": "forward" }

For more information on 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:

A MongoCursor and FindIterable allow you to access query results one document at a time, abstracting away network and caching logic.

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 cur : 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.

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:

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

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:

←  Retrieve DataSort Results →