1Tailable Cursors 2================ 3 4By default, MongoDB will automatically close a cursor when the client has 5exhausted all results in the cursor. However, for `capped collections 6<https://docs.mongodb.org/manual/core/capped-collections/>`_ you may 7use a `tailable cursor 8<https://docs.mongodb.org/manual/reference/glossary/#term-tailable-cursor>`_ 9that remains open after the client exhausts the results in the initial cursor. 10 11The following is a basic example of using a tailable cursor to tail the oplog 12of 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. Starting in MongoDB 4.4 30 # this option is ignored by the server as queries against the oplog 31 # are optimized automatically by the MongoDB query engine. 32 cursor = oplog.find({'ts': {'$gt': ts}}, 33 cursor_type=pymongo.CursorType.TAILABLE_AWAIT, 34 oplog_replay=True) 35 while cursor.alive: 36 for doc in cursor: 37 ts = doc['ts'] 38 print(doc) 39 # We end up here if the find() returned no documents or if the 40 # tailable cursor timed out (no new documents were added to the 41 # collection for more than 1 second). 42 time.sleep(1) 43