Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversKotlin Coroutine

Access Data From a Flow

On this page

  • Overview
  • Terminal Methods
  • Find the First Document
  • Count Number of Results
  • Convert Results to a List
  • Iterate through Results
  • Explain the Query

In this guide, you can learn how to access data using a Flow with the MongoDB Kotlin driver.

A Flow is a data type built into Kotlin coroutines that represent a stream of values that are being computed asynchronously. The Kotlin coroutine driver uses flows to represent the results of database read operations.

This page uses an initiating method, find() to show how to access data from a FindFlow.


The following ways to access and store data apply to other iterables such as an AggregateFlow.

The find() method creates and returns an instance of a FindFlow. A FindFlow 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 server after configuring all parameters of a Flow instance controlling the operation.

Use the firstOrNull() method to retrieve the first document in your query results or null if there are no results:

val resultsFlow = collection.find()
val firstResultOrNull = resultsFlow.firstOrNull()

Alternatively, you can use the first() method to retrieve the first document in your query or throw a NoSuchElementException if there are no results:

try {
val resultsFlow = collection.find()
val firstResult = resultsFlow.first()
} catch (e: NoSuchElementException) {
println("No results found")

These methods are often used when your query filter will match one document, such as when filtering by a unique index.

Use the count() method to retrieve the number of results in the query:

val resultsFlow = collection.find()
val count = resultsFlow.count()

Use the toList() method to store your query results in a List:

val resultsFlow = collection.find()
val results = resultsFlow.toList()

This method is often used when your query filter returns a small number of documents that can fit into available memory.

Use the collect() method to iterate through fetched documents and ensure that the flow closes if there is an early termination:

val resultsFlow = collection.find()
resultsFlow.collect { println(it) }

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
You want to know which plan MongoDB will choose to run your query.
You want to know if your query is performing well.
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:

val explanation = collection.find().explain(ExplainVerbosity.EXECUTION_STATS)
val jsonSummary = explanation.getEmbedded(
listOf("queryPlanner", "winningPlan"),
{ "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:

←  Retrieve DataOpen Change Streams →