【问题标题】:Pymongo - tailing oplog [duplicate]Pymongo - 拖尾 oplog [重复]
【发布时间】:2015-05-27 05:10:49
【问题描述】:

我正在尝试在 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)

我尝试了一些解决方案,但是一旦添加了可尾选项,它仍然会失败。 Oplog 设置正确,因为来自 nodejs 的 mongo-oplog 模块按预期工作。

可能duplicate(不接受答案)

【问题讨论】:

    标签: python mongodb pymongo


    【解决方案1】:

    您需要查询'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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      • 1970-01-01
      • 2016-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多