Python MongoDB - 删除集合
您可以使用 MongoDB 的 drop() 方法删除集合。
语法
以下是 drop() 方法的语法 −
db.COLLECTION_NAME.drop()
示例
以下示例删除名为 sample 的集合 −
> show collections myColl sample > db.sample.drop() true > show collections myColl
使用 Python 删除集合
您可以通过调用 drop() 方法从当前集合中删除集合。
示例
from pymongo import MongoClient
#创建 pymongo 客户端
client = MongoClient('localhost', 27017)
#获取数据库实例
db = client['example2']
#创建集合
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"})
#集合列表
print("List of collections:")
collections = db.list_collection_names()
for coll in collections:
print(coll)
#删除集合
col1.drop()
col4.drop()
print("删除两个集合后的集合列表:")
#集合列表
collections = db.list_collection_names()
for coll in collections:
print(coll)
输出
List of collections: coll data collection myColl List of collections after dropping two of them: coll myColl

