Wednesday, July 3, 2024
HomeLanguagesPythonDrop Collection if already exists in MongoDB using Python

Drop Collection if already exists in MongoDB using Python

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

Syntax:

drop()

Example 1: 

The sample database is as follows: 

 

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
Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments