基于MongoDB实现聊天记录的存储
from pymongo import MongoClient
class ChatRecordStorage:
def __init__(self, connection_string, db_name, collection_name):
self.client = MongoClient(connection_string)
self.db = self.client[db_name]
self.collection = self.db[collection_name]
def add_record(self, record):
self.collection.insert_one(record)
def get_records(self, query):
return list(self.collection.find(query))
# 使用示例
if __name__ == "__main__":
# 替换为你的MongoDB连接信息
connection_string = "mongodb://localhost:27017/"
db_name = "chat_records"
collection_name = "messages"
storage = ChatRecordStorage(connection_string, db_name, collection_name)
# 添加聊天记录
record = {
"sender": "user1",
"recipient": "user2",
"message": "Hello, World!"
}
storage.add_record(record)
# 获取聊天记录
user1_records = storage.get_records({"sender": "user1"})
print(user1_records)
这段代码定义了一个ChatRecordStorage
类,它使用pymongo
库与MongoDB进行交互。你需要替换connection_string
变量的值为你的MongoDB连接信息。这个类提供了添加记录和获取记录的方法,可以用来存储和检索聊天数据。使用时,首先创建一个ChatRecordStorage
实例,然后使用add_record
方法添加记录,使用get_records
方法检索记录。
评论已关闭