Last active
August 7, 2023 13:22
-
-
Save circuitBurn/97441f2f6ded72fc4f1d to your computer and use it in GitHub Desktop.
Use pymongo 3.0 to tail MongoDB's oplog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adapted from the example here: https://jira.mongodb.org/browse/PYTHON-735 | |
# to work with pymongo 3.0 | |
import pymongo | |
from pymongo.cursor import CursorType | |
c = pymongo.MongoClient() | |
# Uncomment this for master/slave. | |
oplog = c.local.oplog['$main'] | |
# Uncomment this for replica sets. | |
#oplog = c.local.oplog.rs | |
first = next(oplog.find().sort('$natural', pymongo.DESCENDING).limit(-1)) | |
ts = first['ts'] | |
while True: | |
cursor = oplog.find({'ts': {'$gt': ts}}, cursor_type=CursorType.TAILABLE_AWAIT, oplog_replay=True) | |
while cursor.alive: | |
for doc in cursor: | |
print doc | |
# Work with doc here | |
ts = doc['ts'] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example is now in the official pymongo documentation: https://pymongo.readthedocs.io/en/stable/examples/tailable.html