Python 如何从MongoDB实时查询数据?
我创建了一个MongoDB数据库,并向它发送数据。同时,我正在运行一个Python脚本来从该数据库获取数据。我希望我的脚本在推送到DB后立即将新条目打印到我的控制台,但我不知道如何实现这一点 这是我目前的工作,但我不喜欢它,因为每次它都会在db上打印整个数据,即使我只想在更新后立即打印最后一个条目:Python 如何从MongoDB实时查询数据?,python,mongodb,Python,Mongodb,我创建了一个MongoDB数据库,并向它发送数据。同时,我正在运行一个Python脚本来从该数据库获取数据。我希望我的脚本在推送到DB后立即将新条目打印到我的控制台,但我不知道如何实现这一点 这是我目前的工作,但我不喜欢它,因为每次它都会在db上打印整个数据,即使我只想在更新后立即打印最后一个条目: from pymongo import MongoClient import time import random from pprint import pprint client = Mongo
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)
如何解决此问题?有几种方法可以处理此问题,但最简单的方法可能是存储一个自动递增的“primaryKey”(或插入时间戳或其他),并仅打印该键之后出现的结果。下面是一个快速示例来演示:
# we start at one...
highest_previous_primary_key = 1
while True:
cursor = db.mycol.find()
for document in cursor:
# get the current primary key, and if it's greater than the previous one
# we print the results and increment the variable to that value
current_primary_key = document['primaryKey']
if current_primary_key > highest_previous_primary_key:
print(document['num'])
highest_previous_primary_key = current_primary_key
time.sleep(2)
这也许是最懒惰的做法。但除此之外,您还可以尝试:
自3.6版起,Mongo DB支持一个功能调用“Change Streams”。在中,您将发现以下简单的Python示例:
cursor = db.inventory.watch()
document = next(cursor)
如果光标上支持
next()
,您也应该能够在循环、生成器甚至asyncio
中使用它。是的,我知道更改流,我认为这是最好的方法,但我尝试过使用它,我发现我只能将它用于副本数据库,而我的数据库不是副本数据库,我正在做更多的测试,问题是有时它会停止打印新条目,就像循环因某种原因而中断一样,你知道为什么吗?正好在记录编号4之后,它会停止运行