Python MongoDB 删除集合

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

#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)

输出

List of collections:
coll
data
collection
myColl
List of collections after dropping two of them:
coll
myColl

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程