Drop Collection if already exists in MongoDB using Python

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:
 

drop()

Example 1: 

Sample Database:



Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output: 

Example 2: If collection does not exist. 
 

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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')

chevron_right


Output:

Not Present
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.