[docs]classGoldyDB():"""A class representing a singular goldy bot database in mongoDB."""def__init__(self,core_database:Database,db_code_name:str)->None:self.client=core_database.clientself.database=self.client[db_code_name]self.logger=LoggerAdapter(core_database.logger,Colours.PINK_GREY.apply_to_string(db_code_name))
[docs]asyncdefinsert(self,collection:str,data)->None:""" Inserts the data provided into a collection in this database. Creates a whole new document. If you want to edit an existing document use .edit() """awaitself.database[collection].insert_one(data)self.logger.debug(f"Inserted '{data}' into '{collection}.'")
[docs]asyncdefedit(self,collection:str,query,data:dict,overwrite:bool=False)->dict:"""Finds and edits a document in this database and collection with the data provided."""ifoverwrite:awaitself.database[collection].update_one(query,{"$set":data},upsert=True)else:document_data=awaitself.find_one("guild_configs",query)data=utils.update_dict(document_data,data)ifdocument_dataisnotNoneelsedataawaitself.database[collection].update_one(query,{"$set":data},upsert=True)self.logger.debug(f"Edited '{query}' with '{data}.'")returnawaitself.find_one(collection,query)
[docs]asyncdefremove(self,collection:str,data)->None:"""Finds and deletes a copy of this data from a collection in this database."""awaitself.database[collection].delete_one(data)self.logger.debug(f"Deleted '{data}' from '{collection}.'")
[docs]asyncdeffind(self,collection:str,query,key:str,max_to_find=50)->List[dict]:"""Searches for and returns documents with that query in a collection in this database."""try:document_list=[]cursor=self.database[collection].find(query).sort(key)fordocumentinawaitcursor.to_list(max_to_find):document_list.append(document)returndocument_listexceptKeyError:self.logger.debug(f"Could not find the collection '{collection}'!")returnNone
[docs]asyncdeffind_all(self,collection:str,max_to_find=100)->List[dict]|None:"""Finds and returns all documents in a collection from this database. This took me a day to make! 😞"""try:document_list=[]cursor=self.database[collection].find().sort('_id')fordocumentinawaitcursor.to_list(max_to_find):document_list.append(document)returndocument_listexceptKeyError:self.logger.debug(f"Could not find the collection '{collection}'!")returnNone
[docs]asyncdeffind_one(self,collection:str,query:dict)->(dict|None):"""Searches for and returns specific data (document) from a collection in this database."""data=awaitself.database[collection].find_one(query)ifdataisnotNone:self.logger.debug(f"Found '{query}' in '{collection}.'")returndataelse:self.logger.debug(f"'{query}' was not found in '{collection}.'")returnNone
[docs]asyncdeflist_collection_names(self)->List[str]:"""Returns list of all collection name in this database."""returnawaitself.database.list_collection_names()