I'm trying to listen to a MongoDB collection, for all docs where the field category
is an empty list, do some stuff to fill the category
field, and then listen to the following incoming docs.
Using these (which are old) :
How to listen for changes to a MongoDB collection?
with Python is there a way to listen for changes when insert or update is made in mongodb
I came up with the following :
client = pymongo.MongoClient(mongodb_uri_connexion_string)
db = client.get_default_database()
my_collection = db['my_collection']
cursor = my_collection.find({'category':[]},cursor_type=pymongo.cursor.CursorType.EXHAUST)
while True:
try:
doc = cursor.next()
# place where computation gets done to find the value of new_cat
my_collection.find_one_and_update({'_id':doc['_id']}, {'$push':{'category':{new_cat:'1'}}})
pprint.pprint(my_collection.find_one({'_id':doc['_id']})
except StopIteration:
print("end of cursor, wait")
time.sleep(0.2)
except Exception as e:
print("another problem came up, see below")
print(exception_to_string(e))
When I run the script, it's doing what it should be doing, printing the doc
s with the category
updated, up until the point it is done with the content of cursor
at the moment the line was run : it's not listening to subsequent new doc
s in my_collection
, I get an infinite number of end of cursor, wait
.
If I change the CursorType
to TAILABLE_AWAIT
, it seems to not even do the computations in the try
block, and jump straight to the infinite printing of end of cursor, wait
What am I doing wrong ? Thanks