我想在MongoDB中模仿Rethinkdb'include_initials'。我认为以下代码有效。如果change_stream在c.find()之前接触了DB,我可以将手表的增量排队,直到查找完成。然后,我将增量应用于本地数据。但是我必须确保change_stream在找到之前先命中数据库,否则,我可能会错过一些更改。
from asyncio import get_event_loop
import asyncio
import motor.motor_asyncio
client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017/?replicaSet=foo')
db = client.test
c = db.test
change_stream = None
async def do_find():
print('do find')
async for document in c.find({}):
print(document)
async def watch_collection():
global change_stream
async with c.watch() as change_stream:
asyncio.create_task(do_find())
print('before changes')
async for change in change_stream:
print(change)
def main():
try:
loop = get_event_loop()
loop.run_until_complete(watch_collection())
except KeyboardInterrupt:
pass
finally:
if change_stream is not None:
change_stream.close()
更新
如果每个文档都带有时间戳“ updated_at”,则可以使用初始数据构建流。 我收到发现的所有数据,然后看到最大的时间戳(我称其为max_t),并使用“ start_at_operation_time”> max_t
进行观看