Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Drop Collection if already exists in MongoDB using Python

  • Last Updated : 26 May, 2020

Using drop() method we can drop collection data if data is already exist. If data is not found then it returns False otherwise it returns True if collection is dropped. 

Syntax:
 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

drop()

Example 1: 



Sample Database:

Python3




import pymongo
  
  
client = pymongo.MongoClient("mongodb://localhost:27017/")
  
# Database name
db = client["mydatabase"]
  
# Collection name
col = db["gfg"]
  
# drop collection col1
print(col.drop())

Output: 

Example 2: If collection does not exist. 
 

Python3




import pymongo
  
  
client = pymongo.MongoClient("mongodb://localhost:27017/")
  
# Database name
db = client["mydatabase"]
  
# Collection name
col = db["gfg"]
  
# drop collection col1
if col.drop():
    print('Deleted')
else:
    print('Not Present')

Output:

Not Present



My Personal Notes arrow_drop_up
Recommended Articles
Page :