All Courses

Python MongoDB - Drop Collection

Neha Kumawat

a year ago

Python MongoDB - Drop Collection
Table of Content
  • Syntax
  • Example
  • Dropping Collection Using Python
You can delete collections using drop() method of MongoDB.

Syntax

Following is the syntax of drop() method −

db.COLLECTION_NAME.drop()

Example

Following example drops collection with name sample −

> show collections
myColl
sample
> db.sample.drop()
true
> show collections
myColl

Dropping Collection Using Python

You can drop/delete a collection from the current by invoking drop() method.

Example


from pymongo import MongoClient

#Creating a pymongo client
client = MongoClient('localhost', 27017)

#Getting the database instance
db = client['example2']

#Creating a collection
col1 = db['collection']
col1.insert_one({"name": "Ram", "age": "26", "city": "Hyderabad"})
col2 = db['coll']
col2.insert_one({"name": "Rahim", "age": "27", "city": "Bangalore"})
col3 = db['myColl']
col3.insert_one({"name": "Robert", "age": "28", "city": "Mumbai"})
col4 = db['data']
col4.insert_one({"name": "Romeo", "age": "25", "city": "Pune"})

#List of collections
print("List of collections:")
collections = db.list_collection_names()
for coll in collections:
   print(coll)

#Dropping a collection
col1.drop()
col4.drop()
print("List of collections after dropping two of them: ")

#List of collections
collections = db.list_collection_names()
for coll in collections:
   print(coll)

Output


List of collections:
coll
data
collection
myColl
List of collections after dropping two of them:
coll
myColl
Enjoyed reading this blog? Then why not share it with others. Help us make this AI community stronger. 
To learn more about such concepts related to Artificial Intelligence, visit our insideAIML blog page.
You can also ask direct queries related to Artificial Intelligence, Deep Learning, Data Science and Machine Learning on our live insideAIML discussion forum.
Keep Learning. Keep Growing.

Submit Review