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
import pymongo # Database name db = client[ "mydatabase" ] # Collection name col = db[ "gfg" ] # drop collection col1 print (col.drop()) |
chevron_right
filter_none
Output:
Example 2: If collection does not exist.
Python3
import pymongo # Database name db = client[ "mydatabase" ] # Collection name col = db[ "gfg" ] # drop collection col1 if col.drop(): print ( 'Deleted' ) else : print ( 'Not Present' ) |
chevron_right
filter_none
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.