确定Python中是否存在MongoDB中的集合
我想知道MongoDB中是否存在特定名称的集合。如何在Python中以编程方式实现这一点。在搜索相同的内容时,我从MongoDB shell了解了如何做到这一点,但在Python中没有任何用处 您可以使用该方法检索并检查@Alex给定的集合是否存在,如下所示: 方法1:确定Python中是否存在MongoDB中的集合,mongodb,python-2.7,Mongodb,Python 2.7,我想知道MongoDB中是否存在特定名称的集合。如何在Python中以编程方式实现这一点。在搜索相同的内容时,我从MongoDB shell了解了如何做到这一点,但在Python中没有任何用处 您可以使用该方法检索并检查@Alex给定的集合是否存在,如下所示: 方法1: import pymongo connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb db = connection['test_
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
list_of_collections = db.list_collection_names() # Return a list of collections in 'test_db'
print("posts" in db.list_collection_names()) # Check if collection "posts" exists in db (test_db)
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
try:
db.validate_collection("random_collection_name") # Try to validate a collection
except pymongo.errors.OperationFailure: # If the collection doesn't exist
print("This collection doesn't exist")
或者,您可以使用validate_collection()
()验证集合。如果集合不存在,则返回错误(pymongo.errors.OperationFailure
)。您还可以捕获该异常并执行任何您想要的操作
方法2:
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
list_of_collections = db.list_collection_names() # Return a list of collections in 'test_db'
print("posts" in db.list_collection_names()) # Check if collection "posts" exists in db (test_db)
import pymongo
connection = pymongo.MongoClient('localhost', 27017) # Connect to mongodb
db = connection['test_db']
try:
db.validate_collection("random_collection_name") # Try to validate a collection
except pymongo.errors.OperationFailure: # If the collection doesn't exist
print("This collection doesn't exist")
可能是@Alex的副本:谢谢。。。这就解决了我的问题:)@Alex:你能把这个作为答案贴出来,这样我就可以接受这个作为最终答案了吗?