-
Notifications
You must be signed in to change notification settings - Fork 10
DOCSP-41139: Cursors #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 8 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
9e3526c
DOCSP-41139: Cursors
mcmorisi edeab1b
Fix
mcmorisi 5d71c43
Fix
mcmorisi 84cc0f8
Address technical feedback
mcmorisi ea8e623
Fix
mcmorisi c538f4b
Fix
mcmorisi ba03d7c
Fix
mcmorisi bde6014
Further technical feedback
mcmorisi 170786f
Fix
mcmorisi 5e58e68
Merge branch 'master' into DOCSP-41139-cursor
mcmorisi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
package org.example | ||
import com.mongodb.ConnectionString | ||
import com.mongodb.CursorType | ||
import com.mongodb.MongoClientSettings | ||
import com.mongodb.client.model.Filters.eq | ||
import com.mongodb.kotlin.client.MongoClient | ||
import org.bson.codecs.pojo.annotations.BsonId | ||
import org.bson.types.ObjectId | ||
import org.bson.Document | ||
|
||
// start-data-class | ||
data class Restaurant( | ||
@BsonId | ||
val id: ObjectId, | ||
val name: String | ||
) | ||
// end-data-class | ||
|
||
fun main() { | ||
val uri = "<connection string URI>" | ||
|
||
val settings = MongoClientSettings.builder() | ||
.applyConnectionString(ConnectionString(uri)) | ||
.retryWrites(true) | ||
.build() | ||
|
||
val mongoClient = MongoClient.create(settings) | ||
val database = mongoClient.getDatabase("sample_restaurants") | ||
val collection = database.getCollection<Restaurant>("restaurants") | ||
|
||
// start-cursor-iterate | ||
val results = collection.find() | ||
|
||
results.forEach { result -> | ||
println(result) | ||
} | ||
// end-cursor-iterate | ||
|
||
// start-cursor-iterate-alternative | ||
val result = collection.find() | ||
|
||
results.cursor().use { cursor -> | ||
while (cursor.hasNext()) { | ||
println(resultCursor.next()) | ||
} | ||
} | ||
// end-cursor-iterate-alternative | ||
|
||
// start-cursor-next | ||
val results = collection | ||
.find<Restaurant>(eq(Restaurant::name.name, "Dunkin' Donuts")) | ||
|
||
results.cursor().use { cursor -> | ||
println(if (cursor.hasNext()) cursor.next() | ||
else "No document matches the filter") | ||
} | ||
// end-cursor-next | ||
|
||
// start-cursor-list | ||
val results = collection.find<Restaurant>(eq(Restaurant::name.name, "Dunkin' Donuts")) | ||
val resultsList = results.toList() | ||
|
||
for (result in resultsList) { | ||
println(result) | ||
} | ||
// end-cursor-list | ||
|
||
// start-tailable-cursor | ||
val results = collection.find<Document>().cursorType(CursorType.TailableAwait) | ||
// end-tailable-cursor | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,173 @@ | ||
.. _kotlin-sync-cursors: | ||
|
||
========================= | ||
Access Data From a Cursor | ||
========================= | ||
|
||
.. contents:: On this page | ||
:local: | ||
:backlinks: none | ||
:depth: 1 | ||
:class: singlecol | ||
|
||
.. facet:: | ||
:name: genre | ||
:values: reference | ||
|
||
.. meta:: | ||
:keywords: read, results, oplog | ||
|
||
Overview | ||
-------- | ||
|
||
In this guide, you can learn how to access data from a **cursor** with the | ||
{+driver-short+}. | ||
|
||
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 the number of requests the driver sends to | ||
the server. | ||
|
||
Whenever the {+driver-short+} performs a read operation that returns multiple | ||
documents, it automatically returns those documents in a cursor. | ||
|
||
Sample Data | ||
~~~~~~~~~~~ | ||
|
||
The examples in this guide use the ``restaurants`` collection in the ``sample_restaurants`` | ||
database from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a | ||
free MongoDB Atlas cluster and load the sample datasets, see the | ||
:atlas:`Get Started with Atlas </getting-started>` guide. | ||
|
||
The following {+language+} data class models the documents in this collection: | ||
|
||
.. literalinclude:: /includes/read/cursors.kt | ||
:start-after: start-data-class | ||
:end-before: end-data-class | ||
:language: kotlin | ||
:copyable: | ||
|
||
.. _kotlin-sync-cursors-iterate: | ||
|
||
Access Cursor Contents Iteratively | ||
---------------------------------- | ||
|
||
To iterate over the contents of a cursor, use the ``forEach()`` method, as shown in the | ||
following example: | ||
|
||
.. literalinclude:: /includes/read/cursors.kt | ||
:start-after: start-cursor-iterate | ||
:end-before: end-cursor-iterate | ||
:language: kotlin | ||
:copyable: | ||
:dedent: | ||
|
||
Alternatively, use the ``use()`` method to implement a loop on the cursor: | ||
|
||
.. literalinclude:: /includes/read/cursors.kt | ||
:start-after: start-cursor-iterate-alternative | ||
:end-before: end-cursor-iterate-alternative | ||
:language: kotlin | ||
:copyable: | ||
:dedent: | ||
|
||
.. note:: | ||
|
||
By default, MongoDB closes a cursor when the client has exhausted all the | ||
results in the cursor. The examples in this guide explicitly close cursors by using the | ||
``close()`` method. | ||
|
||
Retrieve Documents Individually | ||
stIncMale marked this conversation as resolved.
Show resolved
Hide resolved
|
||
------------------------------- | ||
|
||
Retrieve documents from a cursor individually by calling the ``next()`` method. | ||
|
||
The following example finds all documents in a collection with a ``name`` value | ||
of ``"Dunkin' Donuts"``. It then prints the first document in the cursor by calling the | ||
``next()`` method. | ||
|
||
.. io-code-block:: | ||
:copyable: | ||
|
||
.. input:: /includes/read/cursors.kt | ||
:start-after: start-cursor-next | ||
:end-before: end-cursor-next | ||
:language: kotlin | ||
:dedent: | ||
|
||
.. output:: | ||
:visible: false | ||
|
||
Restaurant(id=5eb3d668b31de5d588f42c66, name=Dunkin' Donuts) | ||
|
||
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, :ref:`access your cursor iteratively <kotlin-sync-cursors-iterate>`. | ||
|
||
To retrieve all documents from a cursor, convert the cursor into a ``List`` as | ||
shown in the following example: | ||
|
||
.. io-code-block:: | ||
:copyable: | ||
|
||
.. input:: /includes/read/cursors.kt | ||
:start-after: start-cursor-list | ||
:end-before: end-cursor-list | ||
:language: kotlin | ||
:dedent: | ||
|
||
.. output:: | ||
:visible: false | ||
|
||
Restaurant(id=5eb3d668b31de5d588f42c66, name=Dunkin' Donuts) | ||
Restaurant(id=5eb3d668b31de5d588f42ca0, name=Dunkin' Donuts) | ||
Restaurant(id=5eb3d668b31de5d588f42b08, name=Dunkin' Donuts) | ||
Restaurant(id=5eb3d668b31de5d588f42cd7, name=Dunkin' Donuts) | ||
... | ||
|
||
Tailable Cursors | ||
---------------- | ||
|
||
When querying on a :manual:`capped collection </core/capped-collections/>`, you | ||
can use a **tailable cursor** that remains open after the client exhausts the | ||
results in a cursor. To create a tailable cursor with capped collection, | ||
specify ``CursorType.TailableAwait`` to the ``cursorType`` method of a | ||
``FindIterable`` object. | ||
|
||
The following example creates a tailable cursor on a capped collection: | ||
|
||
.. literalinclude:: /includes/read/cursors.kt | ||
:start-after: start-tailable-cursor | ||
:end-before: end-tailable-cursor | ||
:language: kotlin | ||
:copyable: | ||
:dedent: | ||
|
||
To learn more about tailable cursors and their usage, see the :manual:`Tailable Cursors guide | ||
</core/tailable-cursors/>` in the {+mdb-server+} manual. | ||
|
||
Troubleshooting | ||
--------------- | ||
|
||
"*CursorNotFound* cursor id not valid at server" | ||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | ||
|
||
Cursors in MongoDB can timeout on the server if they've been open for | ||
a long time without any operations being performed on them. This can | ||
lead to a ``CursorNotFound`` exception when you try to iterate through the cursor. | ||
|
||
API Documentation | ||
----------------- | ||
|
||
To learn more about any of the methods or types discussed in this | ||
guide, see the following API documentation: | ||
|
||
- `find() <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-collection/find.html>`__ | ||
- `FindIterable <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-find-iterable/index.html>`__ | ||
- `MongoCursor <{+api+}/mongodb-driver-kotlin-sync/com.mongodb.kotlin.client/-mongo-cursor/index.html>`__ | ||
- `CursorType <{+core-api+}/com/mongodb/CursorType.html>`__ |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.