2

I have the following code:

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)

I get:

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

How am I supposed to get the latest time-stamp from the oplog of the mongo database?

Animesh Pandey
  • 5,900
  • 13
  • 64
  • 130

1 Answers1

0

Following code gives me the last operation on 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

If you want the operation irrespective of the database and collection, just remove new_query from curr.

Animesh Pandey
  • 5,900
  • 13
  • 64
  • 130