How do i set up a python service that (asynchronously) watches change streams of a mongodb.
All i can find on mongodb.com and pymongo docs are the following two approaches, which do not really seem production ready:
Approach mongodb.com:
import os
import pymongo
from bson.json_util import dumps
client = pymongo.MongoClient('<YOUR-MONGO-CONNECT-STRING>')
change_stream = client.changestream.collection.watch()
for change in change_stream:
print(dumps(change))
Approach pymongo docs:
with db.collection.watch() as stream:
while stream.alive:
change = stream.try_next()
print("Current resume token: %r" % (stream.resume_token,))
if change is not None:
print("Change document: %r" % (change,))
continue
time.sleep(10)
I thought about a solution using the watch function as callback for an event loop. Does anybody know an implementation for this?