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