【问题标题】:How to create collection with index if not exists in pymongo?如果 pymongo 中不存在,如何使用索引创建集合?
【发布时间】:2018-03-14 09:02:38
【问题描述】:

我在 pymongo 中使用自动集合创建:

client = MongoClient(url)
db = client.get_default_database()
my_collection = db['my_collection']

我以为它会在最后一条语句中自动创建并添加

index_name = 'my_index'
if index_name not in my_collection.index_information():
     my_collection.create_index(..., name=index_name, unique=False)

不幸的是,这导致了错误

pymongo.errors.OperationFailure: Collection ... doesn't exist

这让我想到,该集合是在第一次保存时创建的。这让我没有地方放置索引创建代码。

那么,问题是:如何使用索引创建集合,但前提是它不存在?

我已阅读此答案https://stackoverflow.com/a/9826294/258483,但不喜欢两次写入存在检查的含义:

client = MongoClient(url)
db = client.get_default_database()
if 'my_collection' not in db.collection_names():
    db.createCollection('my_collection')

my_collection = db['my_collection']
index_name = 'my_index'
if index_name not in my_collection.index_information():
     my_collection.create_index(..., name=index_name, unique=False)   

【问题讨论】:

    标签: python indexing pymongo


    【解决方案1】:

    如您所见,对尚不存在的集合调用 index_information 会引发 OperationFailure。

    直接拨打create_index,无需先检查:

    client = MongoClient(url)
    db = client.get_default_database()
    my_collection = db['my_collection']
    index_name = 'my_index'
    my_collection.create_index(..., name=index_name, unique=False)
    

    如果索引已经存在,MongoDB 服务器会忽略该命令。如果索引不存在,MongoDB 会创建集合(如果需要)和集合上的索引。

    【讨论】:

    • 这会引发OperationFailure 不是吗?
    • 如果索引已经存在,MongoDB服务器会忽略该命令。
    • 情况是集合可以不存在
    • 试试看!您可以在不存在的集合上创建索引,MongoDB 会自动创建该集合。
    猜你喜欢
    • 2018-08-17
    • 2016-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多