【发布时间】: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)
【问题讨论】: