我正在尝试观察 MongoDB 数据库中所有集合的实时变化。我在 https://pymongo.readthedocs.io/en/stable/api/pymongo/database.html#pymongo.database.Database.watch关注 pymongo 文档,但它似乎只适用于单个集合而不是整个数据库:
import pymongo
uri = 'mongodb://localhost:27017/myDBName'
db = client[myDBName]
client = pymongo.MongoClient(uri)
try:
with db.watch(
[{'$match': {'operationType': 'insert'}}]) as stream:
for insert_change in stream:
print(insert_change)
except Exception as e:
print('OOPS!! Some ERROR Occurred')
print(e)
但我收到以下错误:
{aggregate: 1} is not valid for '$changeStream'; a collection is required., full error: {'operationTime': Timestamp(1614185450, 3), 'ok': 0.0, 'errmsg': "{aggregate: 1} is not valid for '$changeStream'; a collection is required.", 'code': 73, 'codeName': 'InvalidNamespace', '$clusterTime': {'clusterTime': Timestamp(1614185450, 3), 'signature': {'hash': b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00', 'keyId': 0}}}
当我将其更改为它时,db.myCollectionName.watch()...
它正在工作。我究竟做错了什么?我尝试使用循环遍历所有集合并监视每个集合,但这只监视数据库中的第一个集合而不是整个范围for collection in collections: