Python Pymongo-tailing oplog
我试图在mongo的oplog集合上实现一个pub/sub。提供的代码可以工作,没有Python Pymongo-tailing oplog,python,mongodb,pymongo,Python,Mongodb,Pymongo,我试图在mongo的oplog集合上实现一个pub/sub。提供的代码可以工作,没有tailable=True选项集(它将返回所有文档),但只要我将其传递到光标,它就不会拾取任何内容(即使在对所需集合进行更改之后) 我正在使用pymongo 2.7.2 while(True): with self.database.connect() as connection: cursor = connection['local'].oplog.rs.find(
tailable=True
选项集(它将返回所有文档),但只要我将其传递到光标,它就不会拾取任何内容(即使在对所需集合进行更改之后)
我正在使用pymongo 2.7.2
while(True):
with self.database.connect() as connection:
cursor = connection['local'].oplog.rs.find(
{'ns': self.collection},
await_data = True,
tailable = True
)
cursor.add_option(_QUERY_OPTIONS['oplog_replay'])
while cursor.alive:
try:
doc = cursor.next()
print doc
except(AutoReconnect, StopIteration):
time.sleep(1)
我尝试了一些解决方案,但一旦添加了可裁剪选项,它仍然失败。Oplog设置正确,因为nodejs的mongo Oplog
模块按预期工作
可能(没有接受的答案)您需要在“ts”oplog字段上查询,并跟踪您最后读取的文档(通过时间戳),以防必须重新创建光标。以下是一个示例,您可以根据自己的需要进行修改:
import time
import pymongo
c = pymongo.MongoClient()
# Uncomment this for master/slave.
# oplog = c.local.oplog['$main']
# Uncomment this for replica sets.
oplog = c.local.oplog.rs
first = oplog.find().sort('$natural', pymongo.DESCENDING).limit(-1).next()
ts = first['ts']
while True:
cursor = oplog.find({'ts': {'$gt': ts}}, tailable=True, await_data=True)
# oplogReplay flag - not exposed in the public API
cursor.add_option(8)
while cursor.alive:
for doc in cursor:
ts = doc['ts']
# Do something...
time.sleep(1)