[英]How can I query data from MongoDB in real-time?
我創建了一個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)
我該如何解決?
從3.6版開始,Mongo DB支持功能調用“ Change Streams”。 在文檔中,您可以找到以下簡單的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)
這也許是最懶的做法。 但除此之外,您可以嘗試執行以下操作:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.