我想知道 MongoDB 中是否存在特定名称的集合。如何在 Python 中以编程方式实现这一点。在搜索相同的内容时,我知道如何从 MongoDB shell 执行此操作,但在 Python 中执行相同操作没有任何用处。
最佳答案
您可以使用该方法从 comment 中检索和检查您的集合是否存在。由@Alex 给出,如下所示:
方法一:
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)
或者,您可以使用 validate_collection()
验证集合( documentation ) 如果集合不存在,则返回错误 ( pymongo.errors.OperationFailure
)。您还可以捕获该异常并做任何您想做的事情。方法二:
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")
关于mongodb - 判断MongoDB中的集合在Python中是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34183158/