如何实时查询MongoDB中的数据?

Jac*_*022 0 python mongodb

我创建了一个MongoDB数据库,我正在向它发送数据.与此同时,我正在运行一个Python脚本来从该数据库中获取数据.我希望我的脚本在将新条目推送到数据库后立即将其打印到我的控制台,但我不知道如何完成此操作.

这是我目前的工作,但我不喜欢它,因为每次它都会在db上打印整个数据,即使我只想更新最后一个条目/条目:

from pymongo import MongoClient
import time
import random
from pprint import pprint

client = MongoClient(port=27017)

arr = []

db = client.one

mycol = client["coll"]



while True:
    cursor = db.mycol.find()
    for document in cursor:
        print(document['num'])
    time.sleep(2)    
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Kla*_* D. 5

从版本3.6开始,Mongo DB支持功能调用"Change Streams".在文档中,您将在其他一些文章中找到这个简单的Python示例:

cursor = db.inventory.watch()
document = next(cursor)
Run Code Online (Sandbox Code Playgroud)

如果next()光标支持你也应该能够在循环,生成器甚至是它中使用它asyncio.