如何从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)    

我该如何解决此问题?

Mongo DB自3.6版本起支持一个名为"更改流"的功能。在文档中,您会发现这个简单的Python示例以及其他示例:

cursor = db.inventory.watch()
document = next(cursor)

如果光标上支持next(),那么您也应该能够在循环、生成器甚至asyncio中使用它。

有几种方法可以处理此问题,但最简单的方法可能是存储一个自动递增的"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)

这也许是最懒惰的方法。但除此之外,你可以尝试做:

  1. 调整查询本身,使其只获取items>primaryKey(想象一下,如果您有十亿个结果,每次都获取所有结果(

最新更新