Python中判断MongoDB中的集合是否存在

POO*_*PTA 14 mongodb python-2.7

我想知道 MongoDB 中是否存在特定名称的集合。我怎样才能在Python中以编程方式实现这一点。在搜索相同内容时,我知道如何从 MongoDB shell 执行此操作,但对于在 Python 中执行相同操作没有任何有用的信息。

Meh*_*edB 16

您可以使用该方法从@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 list_of_collections)  # Check if collection "posts" exists in db (test_db)
Run Code Online (Sandbox Code Playgroud)

validate_collection()或者,您可以使用(文档)验证集合。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")
Run Code Online (Sandbox Code Playgroud)