如何使用 Mongo 引擎从 MongoDB 获取最新的数据库集合
how to get the latest database collection from MongoDB with Mongo Engine
我对 MongoDB 很陌生。我在一个循环中创建了一个数据库。每次(每 2 小时),我从一些来源获取数据并通过 MongoEngine 创建数据集合并根据创建时间命名每个集合(例如 05_01_2021_17_00_30)。
现在,在另一个 python 代码上,我想获取最新的数据库。如何在不知道名称的情况下调用最新的数据库集合?
我在 Whosebug 中看到了一些指南,但代码很旧,现在无法使用。谢谢大家。
我想出了这个答案:
在mongo_setup.py: 当我要创建数据库时,它会以创建时间命名,并将名称保存在文本文件中。
import mongoengine
import datetime
def global_init():
nownow = datetime.datetime.now()
Update_file_name = str(nownow.strftime("%d_%m_%Y_%H_%M_%S"))
# For Shaking hand between Django and the last updated data base, export the name
of the latest database
# in a text file and from there, Django will understand which database is the
latest
Updated_txt = open('.\Latest database to read for Django.txt', '+w')
Updated_txt.write(Update_file_name)
Updated_txt.close()
mongoengine.register_connection(alias='core', name=Update_file_name)
在 Django 中 views.py: 我们将调用文本文件并读取最新的数据库名称:
database_name_text_file = 'directory of the text file...'
db_name_file = open(database_name_text_file, 'r')
db_name = db_name_file.read()
# MongoDb Database
myclient = MongoClient(port=27017)
mydatabase = myclient[db_name]
classagg = mydatabase['aggregation__class']
database_text = classagg.find()
for i in database_text:
....
我对 MongoDB 很陌生。我在一个循环中创建了一个数据库。每次(每 2 小时),我从一些来源获取数据并通过 MongoEngine 创建数据集合并根据创建时间命名每个集合(例如 05_01_2021_17_00_30)。 现在,在另一个 python 代码上,我想获取最新的数据库。如何在不知道名称的情况下调用最新的数据库集合? 我在 Whosebug 中看到了一些指南,但代码很旧,现在无法使用。谢谢大家。
我想出了这个答案: 在mongo_setup.py: 当我要创建数据库时,它会以创建时间命名,并将名称保存在文本文件中。
import mongoengine
import datetime
def global_init():
nownow = datetime.datetime.now()
Update_file_name = str(nownow.strftime("%d_%m_%Y_%H_%M_%S"))
# For Shaking hand between Django and the last updated data base, export the name
of the latest database
# in a text file and from there, Django will understand which database is the
latest
Updated_txt = open('.\Latest database to read for Django.txt', '+w')
Updated_txt.write(Update_file_name)
Updated_txt.close()
mongoengine.register_connection(alias='core', name=Update_file_name)
在 Django 中 views.py: 我们将调用文本文件并读取最新的数据库名称:
database_name_text_file = 'directory of the text file...'
db_name_file = open(database_name_text_file, 'r')
db_name = db_name_file.read()
# MongoDb Database
myclient = MongoClient(port=27017)
mydatabase = myclient[db_name]
classagg = mydatabase['aggregation__class']
database_text = classagg.find()
for i in database_text:
....