How To Drop MongoDB Database And Collection Use Pymongo In Python

In previous article ( How To Connect MongoDB And Create Database Collection In Python Source Code ), we have tell you how to connect to mongoDB server, how to create database and collection use pymongo library in python. In this article we will show you example about how to delete mongoDB collection and database use pymongo in python source code.

1. Drop MongoDB Collection Use Pymongo.

There are two way to drop mongoDB collection.

  1. Use collection object’s drop() method. This method do not return anything, you need to verify the collection has been deleted.
    from pymongo import MongoClient
    
    db_host = 'localhost'
    
    db_port = 27017
    
    # get mongoDB database server connection object.
    client = MongoClient(db_host, db_port)
    
    # get mongoDB database
    db = client[db_name]
    
    # get mongoDB collection
    collection = db[collection_name]
    
    # invoke collection's drop() method to delete it.
    collection.drop()
    
    
  2. Use mongoDB database object’s drop_collection(collection_name) method. This method will return a dictionary object as response. The dictionary object contains key and value to show whether the drop collection action success or not. If the dictionary object contains key ‘ns’, it means the drop action success. If the dictionary object contains key ‘errmsg’, it means the drop action fail with error message.
    # get the database object.
    db = client[db_name]
                
    # invoke db's drop_collection() method to drop a collection and return a python dictionary object.    
    response = db.drop_collection(collection_name)
            
    # if the returned dictionary object contains 'ns' key.
    if 'ns' in response:
                
        print('Database : ', db_name, ', Collection : ', collection_name, ' has been dropped. ')
                
    # if the response contains 'errmsg' key.    
    elif 'errmsg' in response:
                
        print('Database : ', db_name, ', Collection : ', collection_name, ' drop error : ', response['errmsg'], ', Code Name : ', response['codeName'])   
    

2. Drop MongoDB Database Use Pymongo.

There are also two way to drop a mongoDB database use pymongo in python.

  1. Use pymongo.MongoClient class’s drop_database(db_name) method.
    # import pymongo.MongoClient, we will use this class to create MongoDB database server connection object.
    from pymongo import MongoClient
    
    # database host and port number are saved in global variable.
    db_host = 'localhost'
    
    db_port = 27017
    
    # get MongoDB database server connection object.
    client = MongoClient(db_host, db_port)
    
    result = client.drop_database(db_name)
  2. Drop all collections in a mongoDB database in a loop, after all collectoins has been dropped, the database will be dropped automatically. But this method is not efficiency than first method.
     db = client[db_name]
        
    # get all collection name list.
    collection_name_list = db.list_collection_names()
        
    # loop in the collection name list and drop each collection.
    for collection_name in collection_name_list:
            
        db.drop_collection(collection_name)

3. Drop MongoDB Collection And Database Example.

'''
Created on Sep 9, 2020

@author: songzhao
'''

import sys

# import pymongo.
import pymongo

# import pymongo.MongoClient, we will use this class to create MongoDB database server connection object.
from pymongo import MongoClient

# database host and port number are saved in global variable.
db_host = 'localhost'

db_port = 27017

# get MongoDB database server connection object.
client = MongoClient(db_host, db_port)


# check whether the database exist or not.    
def is_mongo_db_exist(db_name):
     
     # get all database name list.    
     db_list = client.list_database_names()    

     if db_name in db_list:
         
         print('Mongo database ', db_name, ' exist.')
         
         return True
         
     else:
          
         print('Mongo database ', db_name, ' do not exist.')
         
         return False
 
     
'''
    Check whether the collection exist or not. 
'''     
def is_collection_exist(db_name, collection_name):
    
     # get the database.
     db = client[db_name]
     
     # get collection list in the database.
     collection_name_ist = db.list_collection_names()
     
     if collection_name in collection_name_ist:
         
         print('Database : ', db_name, ', Collection : ',collection_name  ,' exist.')
         
         return True
         
     else:
         
         print('Database : ', db_name, ', Collection : ',collection_name  ,' do not exist.')
         
         return False
 
 
    
''' 
   This function will drop a collection by invoke the collection's drop() method.
   
   But the drop() method do not return anything. You should confirm the collection 
   
   has been dropped by query it again and return none.

'''
def drop_collection(db_name, collection_name):
    
    # make sure the collection exist in the database.
    if is_collection_exist(db_name, collection_name):
    
        # get the database.
        db = client[db_name]
        # get the collection.
        collection = db[collection_name]
        # drop the collection by invoke the collection's drop() method.
        collection.drop()
    
        print('Database : ', db_name, ', Collection : ', collection_name, ' has been dropped. ')
        
    else:
        
        print('Database : ', db_name, ', Collection : ', collection_name, ' do not exist. ')
        
        
'''
   This function use MongoDB db's drop_collection() method to drop a collection.
   
   The drop_collection() method will return a response object which is a python dictionary.
   
   If the response dictionary contains key 'ns', then it means the collection has been dropped successfully.
   
   If the drop action has error, then the response dictionary will contains key 'errmsg', you can get it to
   
   see detail error message. 

'''            
def drop_collection_return_response(db_name, collection_name):
    
    # If the dropped collection exist.
    if is_collection_exist(db_name, collection_name):
        
        # get the database object.
        db = client[db_name]
            
        # invoke db's drop_collection() method to drop a collection and return a python dictionary object.    
        response = db.drop_collection(collection_name)
        
        # if the returned dictionary object contains 'ns' key.
        if 'ns' in response:
            
            print('Database : ', db_name, ', Collection : ', collection_name, ' has been dropped. ')
            
        # if the response contains 'errmsg' key.    
        elif 'errmsg' in response:
            
            print('Database : ', db_name, ', Collection : ', collection_name, ' drop error : ', response['errmsg'], ', Code Name : ', response['codeName'])   
        
    else:
        
        print('Database : ', db_name, ', Collection : ', collection_name, ' do not exist. ')

'''
   This function will drop a MongoDB database use pymongo.MongoClient class's drop_database() method.

'''
def drop_database_by_mongo_client(db_name):
    
    result = client.drop_database(db_name)
    
    print('Database : ', db_name, ' has been dropped. ') 
    
    is_mongo_db_exist(db_name)
     
'''
   This function will drop all collections in a database, then the database will be dropped automatically.
'''             
def drop_database_by_collection(db_name):
    
    db = client[db_name]
    
    # get all collection name list.
    collection_name_list = db.list_collection_names()
    
    # loop in the collection name list and drop each collection.
    for collection_name in collection_name_list:
        
        db.drop_collection(collection_name)
        
    print('Database : ', db_name, ' has been dropped. ')     
        
    # after drop all collection then the database will be dropped automatically. 
    is_mongo_db_exist(db_name)
    
             
if __name__ == '__main__':
    
    db_name = 'user_account'
    collection_name = 'account_detail'        
    drop_collection_return_response(db_name, collection_name)
    is_collection_exist(db_name, collection_name)
        
    db_name = 'test_db'
    collection_name = 'test_collection'
    drop_collection(db_name, collection_name)
    is_collection_exist(db_name, collection_name)
        
    db_name = 'test_db'
    drop_database_by_collection(db_name)
        
    db_name = 'user_account'
    drop_database_by_mongo_client(db_name)

Below is above example execution output.

Database :  user_account , Collection :  account_detail  exist.
Database :  user_account , Collection :  account_detail  has been dropped. 
Database :  user_account , Collection :  account_detail  do not exist.
Database :  test_db , Collection :  test_collection  exist.
Database :  test_db , Collection :  test_collection  has been dropped. 
Database :  test_db , Collection :  test_collection  do not exist.
Database :  test_db  has been dropped. 
Mongo database  test_db  do not exist.
Database :  user_account  has been dropped. 
Mongo database  user_account  do not exist.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.