Skip to content

Commit b67206d

Browse files
authored
DOCSP-46884 Abort signal support (#979)
1 parent 65f4f5c commit b67206d

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

source/code-snippets/crud/cursor.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,28 @@ async function close(myColl) {
6868
await cursor.close();
6969
// end close cursor example
7070
}
71+
// Abort in-progress operations
72+
async function abort(myColl) {
73+
// start abort cursor example
74+
const controller = new AbortController();
75+
const { signal } = controller;
76+
77+
process.on('SIGINT', () => controller.abort(new Error('^C pressed')));
78+
79+
try {
80+
const cursor = myColl.find({}, { signal });
81+
for await (const doc of cursor) {
82+
console.log(doc);
83+
}
84+
} catch (error) {
85+
if (error === signal.reason) {
86+
console.error('Operation aborted:', error);
87+
} else {
88+
console.error('Unexpected error:', error);
89+
}
90+
}
91+
// end abort cursor example
92+
}
7193

7294
async function run() {
7395
try {
@@ -81,6 +103,7 @@ async function run() {
81103
await fetchAll(orders);
82104
await rewind(orders);
83105
await count(orders);
106+
await abort(orders);
84107
} finally {
85108
await client.close();
86109
}

source/fundamentals/crud/read-operations/cursor.txt

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,3 +165,36 @@ and the {+mdb-server+}:
165165
:language: javascript
166166
:start-after: start close cursor example
167167
:end-before: end close cursor example
168+
169+
Abort
170+
~~~~~
171+
172+
You can cancel cursor operations by using an `abort signal
173+
<{+api+}/types/Abortable.html>`__. This can help you manage your resources by
174+
releasing memory and network resources used by the cursor if they're no longer
175+
needed.
176+
177+
.. note::
178+
179+
This feature is experimental. Aborting a signal closes a connection, which
180+
might cause unnecessary connection reestablishment.
181+
182+
You can pass the ``signal`` command to the following methods:
183+
184+
- ``collection.find()``
185+
- ``collection.findOne()``
186+
- ``collection.aggregate()``
187+
- ``collection.countDocuments()``
188+
- ``db.listCollections()``
189+
- ``db.command()``
190+
191+
To use an abort signal, create an ``AbortController`` instance and extract the
192+
``signal`` from the controller. In this code example, the process listens for a
193+
``SIGINT`` (``Ctrl+C``) to trigger the ``abort()`` method. You can pass the
194+
``signal`` option to the ``find()`` method to abort the cursor operation if the
195+
signal triggers, as shown in the following example:
196+
197+
.. literalinclude:: /code-snippets/crud/cursor.js
198+
:language: javascript
199+
:start-after: start abort cursor example
200+
:end-before: end abort cursor example

0 commit comments

Comments
 (0)