2015-05-22 17 views
11

Sto cercando di implementare un pub/sub sulla raccolta oplog di mongo. Il codice fornito funziona, senzatailable = True set di opzioni (restituirà tutti i documenti), ma non appena lo passo al cursore non raccoglierà nulla (anche dopo aver apportato modifiche nella raccolta desiderata).Pymongo - tailing oplog

Sto usando 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) 

ho provato poche soluzioni, ma non riesce ancora, non appena si aggiunge l'opzione tailable. Oplog è impostato correttamente, dal momento che il modulo mongo-oplog da nodejs funziona come previsto.

Possibili duplicate (senza risposta accettata)

risposta

4

È necessario interrogare sul campo oplog 'ts', e tenere traccia del l'ultimo documento si legge (attraverso il timestamp) nel caso in cui il cursore deve essere ricreato. Ecco un esempio che è possibile modificare in base alle proprie esigenze:

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)