From cb4a80a28a5fc2509f947dc4e0bb3a6206b1b0ec Mon Sep 17 00:00:00 2001 From: Bernie Hackett Date: Tue, 8 Mar 2016 18:06:18 -0800 Subject: [PATCH] PYTHON-1063 - Add an example doc for tailable cursors --- doc/examples/index.rst | 1 + doc/examples/tailable.rst | 41 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 doc/examples/tailable.rst diff --git a/doc/examples/index.rst b/doc/examples/index.rst index c64417802..097a7c0f6 100644 --- a/doc/examples/index.rst +++ b/doc/examples/index.rst @@ -27,3 +27,4 @@ MongoDB, you can start it like so: high_availability mod_wsgi requests + tailable diff --git a/doc/examples/tailable.rst b/doc/examples/tailable.rst new file mode 100644 index 000000000..d8276cc87 --- /dev/null +++ b/doc/examples/tailable.rst @@ -0,0 +1,41 @@ +Tailable Cursors +================ + +By default, MongoDB will automatically close a cursor when the client has +exhausted all results in the cursor. However, for `capped collections +`_ you may +use a `tailable cursor +`_ +that remains open after the client exhausts the results in the initial cursor. + +The following is a basic example of using a tailable cursor to tail the oplog +of a replica set member:: + + import time + + import pymongo + + client = pymongo.MongoClient() + oplog = client.local.oplog.rs + first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next() + print(first) + ts = first['ts'] + + while True: + # The tailable and await_data options make this a tailable cursor. + cursor = oplog.find({'ts': {'$gt': ts}}, + tailable=True, + await_data=True) + # Enable the OplogReplay cursor option. This enables an optimization + # to quickly find the 'ts' value we're looking for. It can only be used + # when querying the oplog. + cursor.add_option(8) + while cursor.alive: + for doc in cursor: + ts = doc['ts'] + print(doc) + # We end up here if the find() returned no documents or if the + # tailable cursor timed out (no new documents were added to the + # collection for more than 1 second). + time.sleep(1) +