Python 如果pymongo中不存在索引,如何创建集合?
我在pymongo使用自动收藏创建:Python 如果pymongo中不存在索引,如何创建集合?,python,indexing,pymongo,Python,Indexing,Pymongo,我在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_inde
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
这让我想到,这个集合是在第一次保存时创建的。这使我没有地方放置索引创建代码
所以,问题是:如何使用索引创建集合,但前提是它不存在
我读过这个答案,但不喜欢它意味着写两次存在检查:
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)
如您所见,对尚不存在的集合调用
index\u information
,会引发操作失败
只需调用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将创建集合(如有必要)和集合上的索引。这将引发
操作失败
不是吗?如果索引已经存在,MongoDB服务器将忽略该命令。情况是集合可以不存在请尝试并查看!您可以在不存在的集合上创建索引,MongoDB会自动创建该集合。