2

我有以下代码:

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

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

4

1 回答 1

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_querycurr.

于 2016-04-11T17:03:26.447 回答