Skip to content

Commit cb4a80a

Browse files
committed
PYTHON-1063 - Add an example doc for tailable cursors
1 parent 57cc383 commit cb4a80a

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

doc/examples/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,4 @@ MongoDB, you can start it like so:
2727
high_availability
2828
mod_wsgi
2929
requests
30+
tailable

doc/examples/tailable.rst

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
Tailable Cursors
2+
================
3+
4+
By default, MongoDB will automatically close a cursor when the client has
5+
exhausted all results in the cursor. However, for `capped collections
6+
<https://docs.mongodb.org/manual/core/capped-collections/>`_ you may
7+
use a `tailable cursor
8+
<https://docs.mongodb.org/manual/reference/glossary/#term-tailable-cursor>`_
9+
that remains open after the client exhausts the results in the initial cursor.
10+
11+
The following is a basic example of using a tailable cursor to tail the oplog
12+
of a replica set member::
13+
14+
import time
15+
16+
import pymongo
17+
18+
client = pymongo.MongoClient()
19+
oplog = client.local.oplog.rs
20+
first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()
21+
print(first)
22+
ts = first['ts']
23+
24+
while True:
25+
# The tailable and await_data options make this a tailable cursor.
26+
cursor = oplog.find({'ts': {'$gt': ts}},
27+
tailable=True,
28+
await_data=True)
29+
# Enable the OplogReplay cursor option. This enables an optimization
30+
# to quickly find the 'ts' value we're looking for. It can only be used
31+
# when querying the oplog.
32+
cursor.add_option(8)
33+
while cursor.alive:
34+
for doc in cursor:
35+
ts = doc['ts']
36+
print(doc)
37+
# We end up here if the find() returned no documents or if the
38+
# tailable cursor timed out (no new documents were added to the
39+
# collection for more than 1 second).
40+
time.sleep(1)
41+

0 commit comments

Comments
 (0)