【问题标题】:Cannot print timestamp from mongodb oplog using pymongo无法使用 pymongo 从 mongodb oplog 打印时间戳
【发布时间】:2016-08-01 18:39:02
【问题描述】:

我有以下代码:

connection = MongoClient('core.mongo.com', 27017)
db = connection['admin']

first = db.oplog.rs.find().sort('$natural', pymongo.DESCENDING).limit(-1).next()
ts = first['ts']

while True:
    cursor = db.oplog.find({'ts': {'$gt': ts}}, tailable=True, await_data=True)
    while cursor.alive:
        for doc in cursor:
            ts = doc['ts']
        time.sleep(1)

我明白了:

Traceback (most recent call last):
  File "tail.py", line 25, in <module>
    ts = first['ts']
  File "/Library/Python/2.7/site-packages/pymongo/cursor.py", line 569, in __getitem__
    "instances" % index)
TypeError: index 'ts' cannot be applied to Cursor instances

我应该如何从 mongo 数据库的oplog 获取最新的时间戳?

【问题讨论】:

    标签: mongodb pymongo mongodb-oplog


    【解决方案1】:

    下面的代码给了我对database_name.collection_name的最后一次操作:

    connection = MongoClient('core.mongo.com', 27017)
    db = connection['admin']
    
    oplog_str = str(connection.local.oplog.rs)
    print oplog_str
    
    new_query = {'ns': {'$in': ['database_name.collection_name']}}
    
    curr = connection.local.oplog.rs.find(new_query).sort('$natural', pymongo.DESCENDING).limit(-1)
    
    for doc_count, doc in enumerate(curr):
        current_time_stamp = doc['ts'].time
        good_date = datetime.datetime.fromtimestamp(current_time_stamp).ctime()
        print doc_count, good_date
    

    如果您想要不考虑数据库和集合的操作,只需从 curr 中删除 new_query

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 2014-10-06
      • 2017-08-07
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      相关资源
      最近更新 更多