Access Data From a Cursor
On this page
Overview
In this guide, you can learn how to access data from a cursor by using the Java Reactive Streams driver.
A cursor is a mechanism that returns the results of a read operation in iterable batches. Because a cursor holds only a subset of documents at any given time, cursors reduce both memory consumption and network bandwidth usage.
In the Java Reactive Streams driver, some streams are backed by cursors. The size of batches used
in these underlying cursors depends on the demand requested on the Subscription
for the
Publisher
. The batch size of data contained by each underlying cursor can be set by
using the FindPublisher.batchSize()
method.
Sample Data
The examples in this guide use the sample_restaurants.restaurants
collection
from the Atlas sample datasets. To learn how to create a
free MongoDB Atlas cluster and load the sample datasets, see the
Get Started guide.
Important
Project Reactor Library
This guide uses the Project Reactor library to consume Publisher
instances returned
by the Java Reactive Streams driver methods. To learn more about the Project Reactor library
and how to use it, see Getting Started
in the Reactor documentation. To learn more about how we use Project Reactor
library methods in this guide, see the Write Data to MongoDB guide.
Access Cursor Contents Iteratively
To iterate over the contents of a cursor, use the Flux.from()
method, as shown in the
following example:
FindPublisher<Document> findPublisher = collection.find(); Flux.from(findPublisher) .doOnNext(x -> System.out.println(x.getString("name"))) .blockLast();
Retrieve All Documents
Warning
If the number and size of documents returned by your query exceeds available application memory, your program will crash. If you expect a large result set, access your cursor iteratively.
To retrieve all documents from a cursor, convert the cursor into a List
, as
shown in the following example:
FindPublisher<Document> findPublisher = collection.find(Filters.eq("name", "Dunkin' Donuts")); List<Document> resultsList = Flux.from(findPublisher).collectList().block();
Tailable Cursors
When querying on a capped collection, you
can use a tailable cursor that remains open after the client exhausts the
results in a cursor. To create a tailable cursor on a capped collection,
pass a value of CursorType.TailableAwait
to the cursorType()
method of a
FindPublisher
object.
The following example creates a tailable cursor on a collection and prints its contents:
FindPublisher<Document> findPublisher = collection.find().cursorType(CursorType.TailableAwait); Flux.from(findPublisher) .doOnNext(System.out::println) .blockLast();
To learn more about tailable cursors and their usage, see the Tailable Cursors guide in the MongoDB Server manual.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: