I have a MongoDB documents in a collection that I want to watch. There is an array in each document I want to watch for updates that can I print.
pipeline = [
{"$match": {"id": id}}, # Each document has a unique id field, not to be confused with "_id".
{"$project": {"log.logs": 1}}
]
cursor = main.watch(pipeline)
I should note, I'm using Motor with MongoDB because my project is asynchronous. Here is my setup.
import motor.motor_asyncio
from dotenv import load_dotenv
from os import getenv
load_dotenv()
MONGO_SERVER_URL = getenv("MONGO_SERVER_URL")
client = motor.motor_asyncio.AsyncIOMotorClient(MONGO_SERVER_URL)
db = client["Example-Collection"]
main = db["users"]
The logs array nested inside the log attribute is what I'm trying to watch for updates. As I'm using PyMongo, I've tried both the following approaches.
async with cursor as stream:
while stream.alive:
change = await stream.try_next()
print(change)
await asyncio.sleep(3)
This one somewhat works, but all I get is the console constantly printing None, even when there are changes being done (I double checked with Atlas to see changes were actually being done).
async with cursor as stream:
async for change in stream:
print(change)
await asyncio.sleep(3)
This is the recommended approach, but it just continues forever doing nothing. It prints nothing to the console and doesn't detect any changes.