python mongodb 基本操作封裝


from pymongo import MongoClient


class Database:
def __init__(self, address, port, database,user,password):
self.client = MongoClient(host=address, port=port)
self.db = self.client.admin
self.db.authenticate(user, password, mechanism='SCRAM-SHA-1')
self.db = self.client[database]

def get_state(self):
return self.client is not None and self.db is not None

def insert_one(self, collection, data):
if self.get_state():
ret = self.db[collection].insert_one(data)
return ret.inserted_id
else:
return ""

def insert_many(self, collection, data):
if self.get_state():
ret = self.db[collection].insert_many(data)
return ret.inserted_id
else:
return ""

def update(self, collection, data):
# data format:
# {key:[old_data,new_data]}
data_filter = {}
data_revised = {}
for key in data.keys():
data_filter[key] = data[key][0]
data_revised[key] = data[key][1]
if self.get_state():
return self.db[collection].update_many(data_filter, {"$set": data_revised}).modified_count
return 0

def find(self, collection, condition, column=None):
if self.get_state():
if column is None:
return self.db[collection].find(condition)
else:
return self.db[collection].find(condition, column)
else:
return None
#查詢的結果要打印的話需要用list轉一下

def delete(self, collection, condition):
if self.get_state():
return self.db[collection].delete_many(filter=condition).deleted_count
return 0




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM