[英]What is the best way to query a mongodb collection using Python 3
首先,讓我在這里解釋項目問題:
我正在開發一個Web應用程序,使用的是CherryPy , PyMongo庫,並且數據庫后端是MongoDB數據庫 ,我正在使用Python 3作為開發語言。
我的數據庫集合包含260.640個文檔,此處格式簡化為:
{"_id":1,"time":"2014-01-01 00:00:00","value":"1.37468"}
集合中的所有文檔都有一個ID(從0到260640)和一個分別增加一分鍾的時間(所以我總共有6個月的數據)。
我在Windows控制台中運行Mongod.exe服務器,在另一個Windows控制台中運行python Web服務器,並使用Google Chrome瀏覽器查看網頁。
我的目標:
我想查詢數據庫集合,所以我可以得到一個HTML表,其中包含兩個日期之間的行,例如:2014-01-01 00:00:00和2014-01-10 00:00:00,並且該表應該然后在CherryPy制作的網頁上查看。
我的問題:
使用問題中此處提供的代碼,我可以查詢數據庫並在網頁上顯示表格,但是當我顯示7200行時,它大約需要30-50秒,這僅是大約5天的數據需要顯示10天或什至一個月的數據,我們談論的是更長的等待時間,問題首先是用戶必須等待,而且如果用戶選擇更長的時間跨度,瀏覽器可能會超時,這會殺死應用程序。
我的慢代碼:
這是當前有效的代碼,但僅作為“標准車”,我需要“超級車”。
def onem(self):
# Get the MongoClient from the PyMongo lib.
client = MongoClient()
# our database name is raw_data
db = client.raw_data
# Get the starting date from the database (returns a valid date string).
date_from = self.getFromDateToDatePickerFromDB();
# Get the end date from the database (returns a valid date string).
date_to = self.getToDateToDatePicker();
# Query the database for the collection of documents.
collection = db.data.find({'time' : {'$gte' : date_from, '$lt' : date_to}})
# Define a variable to hold the temp rows.
html = ""
# for each document in our collection.
for document in collection:
# build the table.
html = html + '''
<tr>
<td>''' + str(int(document['_id'])) + '''</td>
<td>''' + str(document['time']) + '''</td>
<td>''' + str(document['value']) + '''</td>
</tr>
'''
table = '''
<table border="1" celspacing="0" cellpadding="0" width="100%">
<thead>
<tr>
<td>ID</td>
<td>TIME</td>
<td>VALUE</td>
</tr>
</thead>
<tbody>
''' + html + '''
</tbody>
</table>
'''
# return the valid html with the table to a function which
# outputs an html template to the browser.
return self.GetStaticHTML(table)
# Tell CherryPy that we are done working on the webpage and it lets us show it to the browser.
onem.exposed = True
如果您知道有比提供的代碼更好的查詢mongodb數據庫的方法:
collection = db.data.find({'time' : {'$gte' : date_from, '$lt' : date_to}})
或者,如果您知道一種加快數據庫,代碼或其他任何方式的方法,那么我真的很想聽聽。
謝謝,
潛在的兩個弱點會使您的代碼運行緩慢且無法擴展:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.