File tree Expand file tree Collapse file tree 2 files changed +42
-0
lines changed
Expand file tree Collapse file tree 2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change @@ -27,4 +27,5 @@ MongoDB, you can start it like so:
2727 gridfs
2828 high_availability
2929 mod_wsgi
30+ tailable
3031 tls
Original file line number Diff line number Diff line change 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+ # For a regular capped collection CursorType.TAILABLE_AWAIT is the
26+ # only option required to create a tailable cursor. When querying the
27+ # oplog the oplog_replay option enables an optimization to quickly
28+ # find the 'ts' value we're looking for. The oplog_replay option
29+ # can only be used when querying the oplog.
30+ cursor = oplog.find({'ts': {'$gt': ts}},
31+ cursor_type=pymongo.CursorType.TAILABLE_AWAIT,
32+ oplog_replay=True)
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+
You can’t perform that action at this time.
0 commit comments