This question already has answers here:
How can Python Observe Changes to Mongodb's Oplog

(4个答案)


5年前关闭。




我正在尝试在mongo的oplog集合上实现pub/sub。提供的代码有效,没有设置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)

我尝试了几种解决方案,但是添加了tailable选项后,该解决方案仍然无法通过。 Oplog已正确设置,因为来自nodejs的mongo-oplog模块按预期工作。

可能是duplicate(没有可接受的答案)

最佳答案

您需要在“ts”操作日志字段中进行查询,并跟踪您上一次阅读的文档(通过时间戳),以防必须重新创建Cursor。您可以根据需要修改以下示例:

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)

关于python - pymongo-拖尾oplog,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30401063/

10-11 00:06