Open In App

Drop Collection if already exists in MongoDB using Python

Last Updated : 14 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy