Python 如何在PyMongo中检查集合是否存在以及是否存在空(从集合中删除所有)?

Python 如何在PyMongo中检查集合是否存在以及是否存在空(从集合中删除所有)?,python,mongodb,pymongo,Python,Mongodb,Pymongo,如何在PyMongo中检查集合是否存在以及是否存在空(从集合中删除所有)? 我已经试过了 collection.remove() 或 但它不会删除集合。如何操作?您应该使用.drop()而不是.remove(),有关详细信息,请参阅文档: ===== 对不起,误解了你的问题 要检查集合是否存在,请在数据库上使用方法集合\u name: >>> collection_name in database.list_collection_names() 要检查集合是否为空,请使用:

如何在PyMongo中检查集合是否存在以及是否存在空(从集合中删除所有)? 我已经试过了

collection.remove()

但它不会删除集合。如何操作?

您应该使用
.drop()
而不是
.remove()
,有关详细信息,请参阅文档:

=====

对不起,误解了你的问题


要检查集合是否存在,请在数据库上使用方法
集合\u name

>>> collection_name in database.list_collection_names()
要检查集合是否为空,请使用:

>>> collection.count() == 0
两者都将在结果中返回True或False。

您是否尝试过以下方法:


db.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. 

db.collection.remove()仅从集合中删除与remove中给定的查询匹配的所有记录。例如db.collection.remove({name:'abc'})将删除名为“abc”的所有记录,remove中的空查询将导致删除所有记录,但集合将保持原样。是否确实要在每次检查集合是否存在时都查询数据库中的所有集合?@MoatazElmasry,检查集合是否存在的方法尚未在mongodb中实现,您可以检查此问题:@MoatazElmasry同时,如果您确实需要优化应用程序的性能,您可以求助于其他技术,例如预缓存集合结果。
collection\u names
不推荐使用。改用
列出集合名称
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.