Tailable Cursors

By default, MongoDB will automatically close a cursor when the client hasexhausted all results in the cursor. However, for capped collections you mayuse a tailable cursorthat 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 oplogof a replica set member:

  1. import time
  2.  
  3. import pymongo
  4.  
  5. client = pymongo.MongoClient()
  6. oplog = client.local.oplog.rs
  7. first = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()
  8. print(first)
  9. ts = first['ts']
  10.  
  11. while True:
  12. # For a regular capped collection CursorType.TAILABLE_AWAIT is the
  13. # only option required to create a tailable cursor. When querying the
  14. # oplog the oplog_replay option enables an optimization to quickly
  15. # find the 'ts' value we're looking for. The oplog_replay option
  16. # can only be used when querying the oplog.
  17. cursor = oplog.find({'ts': {'$gt': ts}},
  18. cursor_type=pymongo.CursorType.TAILABLE_AWAIT,
  19. oplog_replay=True)
  20. while cursor.alive:
  21. for doc in cursor:
  22. ts = doc['ts']
  23. print(doc)
  24. # We end up here if the find() returned no documents or if the
  25. # tailable cursor timed out (no new documents were added to the
  26. # collection for more than 1 second).
  27. time.sleep(1)