【问题标题】:Determine whether collection in MongoDB exists in PythonPython中判断MongoDB中的集合是否存在
【发布时间】:2021-04-21 19:36:37
【问题描述】:

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

【问题讨论】:

标签: mongodb python-2.7


【解决方案1】:

您可以使用该方法从@Alex 给出的comment 中检索并检查您的收藏是否存在,如下所示:

方法一:

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")

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    • 2016-01-25
    • 2013-08-19
    相关资源
    最近更新 更多