-
Notifications
You must be signed in to change notification settings - Fork 24
DOCSP-49067: Cursors #584
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
mcmorisi
merged 6 commits into
mongodb:docsp-45382-comp-cvg
from
mcmorisi:DOCSP-49067-cursors
Apr 16, 2025
Merged
DOCSP-49067: Cursors #584
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
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 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,179 @@ | ||
.. _csharp-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** by using the | ||
{+driver-short+}. | ||
|
||
A cursor is a tool 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. | ||
|
||
You can retrieve a cursor by using the ``FindSync()`` or ``FindAsync()`` method. You can | ||
also convert the results of the ``Find()`` method to a cursor by chaining the ``ToCursor()`` | ||
or ``ToCursorAsync()`` method. | ||
|
||
Sample Data | ||
~~~~~~~~~~~ | ||
|
||
The examples in this guide use the ``restaurants`` collection | ||
in the ``sample_restaurants`` database provided in the :atlas:`Atlas sample datasets </sample-data>`. | ||
To learn how to create a free MongoDB Atlas cluster and load the sample datasets, | ||
see the :ref:`<csharp-get-started>` tutorial. | ||
|
||
The examples on this page use the following ``Restaurant`` object to model the documents | ||
in the ``restaurants`` collection: | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-restaurant-class | ||
:end-before: end-restaurant-class | ||
:language: csharp | ||
|
||
.. _csharp-cursors-iterate: | ||
|
||
Access Cursor Contents Iteratively | ||
---------------------------------- | ||
|
||
To iterate over the contents of a cursor, use a ``foreach`` loop inside a ``using`` block. | ||
The following example retrieves documents from the ``restaurants`` collection in which the | ||
value of the ``name`` field is ``"Starbucks"``, then iterates over the results. | ||
Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` tab to see the corresponding | ||
code: | ||
|
||
.. tabs:: | ||
|
||
.. tab:: Synchronous | ||
:tabid: sync | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-cursor-iterate | ||
:end-before: end-cursor-iterate | ||
:language: csharp | ||
:dedent: | ||
|
||
.. tab:: Asynchronous | ||
:tabid: async | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-cursor-iterate-async | ||
:end-before: end-cursor-iterate-async | ||
:language: csharp | ||
:dedent: | ||
|
||
The following example performs the same operation but uses the ``ToCursor()`` method. | ||
Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` | ||
tab to see the corresponding code: | ||
|
||
.. tabs:: | ||
|
||
.. tab:: Synchronous | ||
:tabid: sync | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-cursor-iterate-to-cursor | ||
:end-before: end-cursor-iterate-to-cursor | ||
:language: csharp | ||
:dedent: | ||
|
||
.. tab:: Asynchronous | ||
:tabid: async | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-cursor-iterate-to-cursor-async | ||
:end-before: end-cursor-iterate-to-cursor-async | ||
:language: csharp | ||
:dedent: | ||
|
||
Retrieve All Documents | ||
---------------------- | ||
|
||
.. warning:: | ||
|
||
If the number and size of documents returned by your query exceeds available | ||
application memory, your program might crash. If you expect a large result | ||
set, :ref:`access your cursor iteratively <csharp-cursors-iterate>`. | ||
|
||
To retrieve all documents from a cursor, use the ``ToList()`` method, as shown in the | ||
following example. Select the :guilabel:`Synchronous` or :guilabel:`Asynchronous` | ||
tab to see the corresponding code: | ||
|
||
.. tabs:: | ||
|
||
.. tab:: Synchronous | ||
:tabid: sync | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-cursor-to-list | ||
:end-before: end-cursor-to-list | ||
:language: csharp | ||
:dedent: | ||
|
||
.. tab:: Asynchronous | ||
:tabid: async | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-cursor-to-list-async | ||
:end-before: end-cursor-to-list-async | ||
:language: csharp | ||
:dedent: | ||
|
||
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, create a ``FindOptions`` object and set the | ||
``CursorType`` property to ``CursorType.TailableAwait``. Then, pass the ``FindOptions`` object | ||
to one of the find operation methods. The following example shows how to create a tailable | ||
cursor on a capped collection. Select the :guilabel:`Synchronous` or | ||
:guilabel:`Asynchronous` tab to see the corresponding code: | ||
|
||
.. tabs:: | ||
|
||
.. tab:: Synchronous | ||
:tabid: sync | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-tailable-cursor | ||
:end-before: end-tailable-cursor | ||
:language: csharp | ||
:dedent: | ||
|
||
.. tab:: Asynchronous | ||
:tabid: async | ||
|
||
.. literalinclude:: /includes/fundamentals/code-examples/Cursor.cs | ||
:start-after: start-tailable-cursor-async | ||
:end-before: end-tailable-cursor-async | ||
:language: csharp | ||
:dedent: | ||
|
||
API Documentation | ||
----------------- | ||
|
||
To learn more about the methods and classes used in this guide, see the | ||
following API documentation: | ||
|
||
- `FindSync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.FindSync.html>`__ | ||
- `FindAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollection-1.FindAsync.html>`__ | ||
- `Find() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.Find.html>`__ | ||
- `IAsyncCursor<TDocument> <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IAsyncCursor-1.html>`__ | ||
- `FindOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.FindOptions.html>`__ |
This file contains 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,155 @@ | ||
using System.Threading.Tasks; | ||
using MongoDB.Bson; | ||
using MongoDB.Bson.Serialization.Attributes; | ||
using MongoDB.Driver; | ||
|
||
public class Cursor | ||
{ | ||
// Replace with your connection string | ||
private const string MongoConnectionString = "<connection URI>"; | ||
|
||
public static async Task Main(string[] args) | ||
{ | ||
var mongoClient = new MongoClient(MongoConnectionString); | ||
var database = mongoClient.GetDatabase("sample_restaurants"); | ||
var collection = database.GetCollection<Restaurant>("restaurants"); | ||
|
||
{ | ||
// start-cursor-iterate | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Starbucks"); | ||
|
||
using (var cursor = collection.FindSync(filter)) | ||
{ | ||
while (cursor.MoveNext()) | ||
{ | ||
foreach (var restaurant in cursor.Current) | ||
{ | ||
Console.WriteLine(restaurant.Name); | ||
} | ||
} | ||
} | ||
// end-cursor-iterate | ||
} | ||
|
||
{ | ||
// start-cursor-iterate-async | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Starbucks"); | ||
|
||
using (var cursor = await collection.FindAsync(filter)) | ||
{ | ||
while (await cursor.MoveNextAsync()) | ||
{ | ||
foreach (var restaurant in cursor.Current) | ||
{ | ||
Console.WriteLine(restaurant.Name); | ||
} | ||
} | ||
} | ||
// end-cursor-iterate-async | ||
} | ||
|
||
{ | ||
// start-cursor-iterate-to-cursor | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Starbucks"); | ||
|
||
using (var cursor = collection.Find(filter).ToCursor()) | ||
{ | ||
while (cursor.MoveNext()) | ||
{ | ||
foreach (var restaurant in cursor.Current) | ||
{ | ||
Console.WriteLine(restaurant.Name); | ||
} | ||
} | ||
} | ||
// end-cursor-iterate-to-cursor | ||
} | ||
|
||
{ | ||
// start-cursor-iterate-to-cursor-async | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Starbucks"); | ||
|
||
using (var cursor = await collection.Find(filter).ToCursorAsync()) | ||
{ | ||
while (await cursor.MoveNextAsync()) | ||
{ | ||
foreach (var restaurant in cursor.Current) | ||
{ | ||
Console.WriteLine(restaurant.Name); | ||
} | ||
} | ||
} | ||
// end-cursor-iterate-to-cursor-async | ||
} | ||
|
||
{ | ||
// start-cursor-to-list | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Dunkin' Donuts"); | ||
var results = collection.FindSync(filter).ToList(); | ||
// end-cursor-to-list | ||
} | ||
|
||
{ | ||
// start-cursor-to-list-async | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Dunkin' Donuts"); | ||
var results = (await collection.FindAsync(filter)).ToList(); | ||
// end-cursor-to-list-async | ||
} | ||
|
||
{ | ||
// start-tailable-cursor | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Dunkin' Donuts"); | ||
var options = new FindOptions<Restaurant> | ||
{ | ||
CursorType = CursorType.TailableAwait | ||
}; | ||
|
||
using (var cursor = collection.FindSync(filter, options)) | ||
{ | ||
while (cursor.MoveNext()) | ||
{ | ||
foreach (var restaurant in cursor.Current) | ||
{ | ||
Console.WriteLine(restaurant.Name); | ||
} | ||
} | ||
} | ||
// end-tailable-cursor | ||
} | ||
|
||
{ | ||
{ | ||
// start-tailable-cursor-async | ||
var filter = Builders<Restaurant>.Filter.Eq(r => r.Name, "Dunkin' Donuts"); | ||
var options = new FindOptions<Restaurant> | ||
{ | ||
CursorType = CursorType.TailableAwait | ||
}; | ||
|
||
using (var cursor = await collection.FindAsync(filter, options)) | ||
{ | ||
while (await cursor.MoveNext()) | ||
{ | ||
foreach (var restaurant in cursor.Current) | ||
{ | ||
Console.WriteLine(restaurant.Name); | ||
} | ||
} | ||
} | ||
// end-tailable-cursor-async | ||
} | ||
} | ||
|
||
} | ||
} | ||
|
||
// start-restaurant-class | ||
[BsonIgnoreExtraElements] | ||
public class Restaurant | ||
{ | ||
public ObjectId Id { get; set; } | ||
|
||
[BsonElement("name")] | ||
public string Name { get; set; } | ||
} | ||
// end-restaurant-class |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
S: for all examples, consider showing some output to demonstrate the differences in how results look when accessing iteratively vs from a list, etc
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pretty sure there's no difference in output between cursors and lists, it's just differences in program flow. With the current filters this would just be printing Starbucks/Dunkin' Donuts a bunch. I'm not sure including output would help illustrate any functionality differences. Should I tweak the filters so it at least prints different restaurant names?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that showing a print statement in the code example might lead users to expect an output block, but it's up to you.