Skip to content
Related Articles

Related Articles

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:
 

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

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :