1.实现键值对存取功能
# mongo_key_value_store.py
from pymongo import MongoClient
'''
Mongodb连接类,进行类似redis一样的get,set,delete功能;减轻后面查询工作量
'''
class MongoKeyValueStore:
def __init__(self, uri, db_name, collection_name):
self.client = MongoClient(uri)
self.db = self.client[db_name]
self.collection = self.db[collection_name]
def set(self, key, value):
document = {
'key': key,
'value': value
}
self.collection.replace_one({'key': key}, document, upsert=True)
def get(self, key):
document = self.collection.find_one({'key': key})
return document['value'] if document else None
def delete(self, key):
self.collection.delete_one({'key': key})
def close(self):
self.client.close()
# 创建一个单例或全局的MongoKeyValueStore实例供其他模块使用
_mongo_store = None
def get_mongo_store(uri='mongodb://scu2024b21:b846724a06f490e2@114.115.206.93:27017/scu2024b21', db_name='scu2024b21', collection_name='scu2024b21'):
global _mongo_store
if _mongo_store is None:
_mongo_store = MongoKeyValueStore(uri, db_name, collection_name)
return _mongo_store
# 提供关闭连接的函数
def close_mongo_store():
global _mongo_store
if _mongo_store is not None:
_mongo_store.close()
_mongo_store = None
#测试mongodb连接及设置数据
# _mongo_store=get_mongo_store()
# _mongo_store.set('test', 'hello')
# print(_mongo_store.get('test'))
# _mongo_store.delete('test')
# print(_mongo_store.get('test'))
2.python操作mongodb
- 连接MongoDB数据库:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
- 创建数据库
在pymongo中,数据库是惰性创建的,即当尝试访问一个不存在的数据库时,MongoDB会自动创建它。你可以通过如下方式访问或创建数据库:
db = client['myDatabase']
- 创建集合
集合也是惰性创建的
collection = db['myCollection']
- 插入数据
data = {"name": "John", "age": 25}
collection.insert_one(data)
- 查询数据
find_one()或find()函数来查询数据:
result = collection.find_one({"name": "John"})
results = collection.find({"age": {"$gt": 20}}) # 查询年龄大于20的所有文档 # 遍历查询结果并打印
for res in resilts:
print(res)
- 更新数据
使用update_one()或update_many()函数来更新数据:
new_values = {"$set": {"age": 30}}
collection.update_one({"name": "John"}, new_values)
- 删除数据
使用delete_one()或delete_many()函数来删除数据:
collection.delete_one({"name": "John"})