1. 程式人生 > >python刪除mongodb某資料庫下所有集合,集合重新命名

python刪除mongodb某資料庫下所有集合,集合重新命名

1、在使用mongodb中,有時候會產生一些臨時集合,想要一次把這些臨時集合全部刪除,可以使用python的pymongo模組。
主程式:

from MongoDbHandlerNew import MongoDbHandlerNew
if __name__ == "__main__":
    mongoSession =MongoDbHandlerNew('127.0.0.1','使用者名稱', '密碼','admin')
    allCollectionNames = mongoSession.get_all_colls("Attachment")
    for collection in
allCollectionNames: mongoSession.drop("Attachment", collection) mongoSession.renameCollectionName("Attachment","A","B")#集合A名字改為B mongoSession.close()

MongoDbHandlerNew.py中init函式用來初始化資料庫,get_all_colls函式用來獲取某資料庫下所有集合的名字。

from pymongo import MongoClient
class MongoDbHandlerNew(object)
:
def __init__(self, ip, user=None, keyword=None,authentication=None): if user == None or keyword == None or authentication==None: URL = 'mongodb://{0}'.format(ip) else: URL = 'mongodb://{0}:{1}@{2}/{3}'.format(user, keyword, ip,authentication) self.__Client = MongoClient(URL) def
get_all_colls(self, db):
self.__db = self.__Client[db] result = self.__db.collection_names() return result def renameCollectionName(self, db, collection, collectionNew): _db = self.__Client[db] _collection = _db[collection] result = _collection.rename(collectionNew)