无法使用pymongo从mongodb oplog打印时间戳

时间:2016-04-11 14:22:35

标签: mongodb pymongo mongodb-oplog

我有以下代码:

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获取最新的时间戳?

1 个答案:

答案 0 :(得分:0)

以下代码为我提供了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

如果您想要操作而不管数据库和集合,只需从new_query删除curr