将 mongodb 集合中的文档副本存储在字典列表中,并使用此数据而不是查询数据库是个好主意吗?

Max*_*man 5 python mongodb pymongo discord.py

我目前正在开发一个 Python Discord 机器人,它使用 Mongo 数据库来存储用户数据。

随着这些数据不断变化,数据库将接受大量查询以提取和更新数据;所以我试图找到减少客户端-服务器通信并减少机器人响应时间的方法。

从这个意义上说,在脚本运行后立即创建一个 Mongo 集合的副本作为字典列表,并离线操作数据而不是不断查询数据库是个好主意吗?

特别是,每次使用 collection.find() 方法搜索数据时,都会从列表中提取数据。另一方面,每次需要使用 collection.update() 更新数据时,都会更新列表和数据库。

我将举一个例子来更好地解释我正在尝试做什么。假设我的集合包含具有以下结构的文档:

{"user_id": id_of_the_user, "experience": current_amount_of_experience}
Run Code Online (Sandbox Code Playgroud)

并且经验值必须不断增加。

这是我目前实施它的方式:

online_collection = db["collection_name"] # mongodb cursor
offline_collection = list(online_collection.find()) # a copy of the collection

def updateExperience(user_id):

    online_collection.update_one({"user_id":user_id}, {"$inc":{"experience":1}})
    
    mydocument = next((document for document in offline_documents if document["user_id"] == user_id))
    mydocument["experience"] += 1

def findExperience(user_id):

    mydocument = next((document for document in offline_documents if document["user_id"] == user_id))
    return mydocument["experience"]
Run Code Online (Sandbox Code Playgroud)

如您所见,数据库仅涉及更新功能。

这是一种有效的方法吗?对于非常大的集合(数百万个文档),next () 函数是否具有相同的执行时间,或者仍然会有一些减速?

此外,虽然在问题中没有明确提出,但我很乐意就如何提高 Discord 机器人的性能获得任何建议,只要它不包括使用 VPS 或分片,因为我是已经在使用这些选项。