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:

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

Previous topic

Server Selector Example

Next topic

TLS/SSL and PyMongo

This Page

Quick search