Python mongoHelper模块
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Defines a MongoOperator class and allows you to manipulate the Mongodb Database.(insert, delete, update, select...) ''' from pymongo import MongoClient, errors class MongoOperator(object): ''' MongoOperator class allows you to manipulate the Mongodb Database. :Usage: ''' def __init__(self, **login): ''' The constructor of Mongodb class. Creates an instance of MongoOperator and starts connecting to the Mongodb server's test database. :Args: - **login - Keyword arguments used in MongoClient() and Database.authenticate() functions in order to connect to test database and authenticate clients (including host, user, password...) ''' # connectin to test database: self.__db = MongoClient(login['host'], login['port'])[login['database']] self.__db.authenticate(login['user'], login['password']) def insertOne(self, document, *, collection='test'): ''' Insert one document into collection named test in Mongodb database. :Args: - document - dict. One document to execute insertion. - colletion - str. Named keyword argument used to specify which collection to insert. ''' # select a collection to execute insert operation: test = self.__db[collection] # insert transaction begin: try: result = test.insert_one(document) print('>> MongoDB insertOne operation success.') print('>> Inserted ID:',result.inserted_id) except errors.PyMongoError as e: print('>> MongoDB insertOne operation fail:', type(e), e.details) # add exception logging function later: def insertMany(self, *documents, collection='test'): ''' Insert many document into collection named test in Mongodb database. :Args: - *documents - list of document in variable arguments. Many documents(require more than one) to execute insertion. - colletion - str. Named keyword argument used to specify which collection to insert. ''' # params check: if len(documents) <= 0: raise ValueError("Documents can't be empty.") elif len(documents) <= 1: raise TypeError("MongoDB insertMany Operation need more then one record.") # select a collection to execute insert operation: test = self.__db[collection] # insert transaction begin: try: results = test.insert_many(documents) print('>> MongoDB insertMany operation success.') print('>> Inserted IDs:', results.inserted_ids) except errors.PyMongoError as e: print('>> MongoDB insertMany operation fail:', type(e), e.details) # add exception logging function later: def delete(self, filter, *, collection='test', many=False): ''' Delete a single or many documents matching the filter from collection test in Mongodb database. :Args: - filter - A query that matches the document to delete. - many - bool. Named keyword argument. If True, execute delete_many(); If not, then execute delete_one(). - colletion - str. Named keyword argument used to specify which collection to delete. ''' # select a collection to execute delete operation: test = self.__db[collection] # delete transaction begin: try: results = test.delete_many(filter) if many else test.delete_one(filter) # waiting for test: print('>> MongoDB delete operation success.') print('>> Delete Information:', results.raw_result) print('>> Delete document count:', results.deleted_count) except errors.PyMongoError as e: print('>> MongoDB delete operation fail:', type(e), e) # add exception logging function later: def select(self, filter=None, *, collection='test', many=False): ''' Select a single or many documents matching the filter from collection test in Mongodb database. :Args: - filter - A query that matches the document to select. - many - bool. Named keyword argument. If True, execute find(); If not, then execute find_one(). - colletion - str. Named keyword argument used to specify which collection to select. :Returns: - results - If select success, returns a Cursor instance for navigating select results. If not, returns None. ''' # selcet a collection to execute select operation: test = self.__db[collection] # select transaction begin: try: results = test.find(filter, no_cursor_timeout=True) if many else test.find_one(filter) # waiting for test: print('>> MongoDB select operation success.', type(results)) except errors.PyMongoError as e: print('>> MongoDB select operation fail:', type(e), e) results = None # add exception logging function later: finally: return results def update(self, filter, update, *, collection='test', many=False): ''' Update a single or many documents matching the filter from collection test in Mongodb database. :Args: - filter - A query that matches the document to update. - update - The modifications to apply. - many - bool. Named keyword argument. If True, execute update_many(); If not, then execute update_one(). - colletion - str. Named keyword argument used to specify which collection to update. ''' # select a collection to execute update operation: test = self.__db[collection] # update transaction begin: try: results = test.update_many(filter, update) if many else test.update_one(filter, update) # waiting for test: print('>> MongoDB update operation success:', type(results), results) print('>> Update Information:', results.raw_result) print('>> Matching Counts:', results.matched_count) print('>> Modified Counts:', results.modified_count) except errors.PyMongoError as e: print('>> MongoDB update operation fail:', type(e), e) # add exception logging function later: # test: if __name__ == '__main__': logIn = {'host': 'localhost', 'port': 27017, 'database': 'test', 'user': '', 'password': ''} documents = [{'id': 1, 'name': 'zty'}, {'id': 2, 'name': 'zzz'}, {'id': 3, 'name': 'ttt'}] document = {'id': 1, 'name': 'zty'} mongoHandler = MongoOperator(**logIn) for document in mongoHandler.select({'name': 'zty'}, many=True): print(document) mongoHandler.insertOne(document) print(mongoHandler.select({'name': 'zty'})) mongoHandler.insertMany(*documents) for document in mongoHandler.select({'name': 'zty'}, many=True): print(document) mongoHandler.update({'name': 'zty'}, {'$set': {'name': 'yyy'}}, many=True) for document in mongoHandler.select({'name': 'zzz'}, many=True): print(document) mongoHandler.delete({'name': 'zzz'}, many=True) for document in mongoHandler.select({'name': 'zzz'}, many=True): print(document)