如何在 PyMongo 中检查集合是否存在,如果存在则检查是否为空(从集合中删除所有内容)?
我已经尝试过类似于
collection.remove()
或者collection.remove({})
但它不会删除集合。怎么做?
Pymongo示例代码,包括注释作为说明:
from pymongo import MongoClient
connection = MongoClient('localhost', 27017) #Connect to mongodb
print(connection.database_names()) #Return a list of db, equal to: > show dbs
db = connection['testdb1'] #equal to: > use testdb1
print(db.list_collection_names()) #Return a list of collections in 'testdb1'
print("posts" in db.list_collection_names()) #Check if collection "posts"
# exists in db (testdb1)
collection = db['posts']
print(collection.count() == 0) #Check if collection named 'posts' is empty
collection.drop() #Delete(drop) collection named 'posts' from db and all documents contained.
建议使用.drop()
而不是.remove()
,请查看文档以获取详细信息:http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.drop
=====
抱歉误解了您的问题。
要检查集合是否存在,请在数据库上使用collection_names
方法:
>>> collection_name in database.list_collection_names()
检查集合是否为空,请使用:
if(集合.isEmpty())
>>> collection.count() == 0
两者返回的结果都是True或False。
collection_names
已弃用,请使用 list_collection_names
代替。 - Nigel AinscoeDROP TABLE
)也是如此。 - Reorx