Dim*_*ims 3 python indexing pymongo
我在 pymongo 中使用自动集合创建:
client = MongoClient(url)
db = client.get_default_database()
my_collection = db['my_collection']
Run Code Online (Sandbox Code Playgroud)
我以为它会在最后一条语句中自动创建并添加
index_name = 'my_index'
if index_name not in my_collection.index_information():
my_collection.create_index(..., name=index_name, unique=False)
Run Code Online (Sandbox Code Playgroud)
不幸的是,这导致了错误
pymongo.errors.OperationFailure: Collection ... doesn't exist
Run Code Online (Sandbox Code Playgroud)
这让我想到,该集合是在第一次保存时创建的。这让我没有地方放置索引创建代码。
所以,问题是:如何创建带有索引的集合,但前提是它不存在?
我已阅读此答案/sf/answers/687840611/,但不喜欢它意味着两次写入存在检查:
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)
Run Code Online (Sandbox Code Playgroud)
如您所见,调用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)
Run Code Online (Sandbox Code Playgroud)
如果索引已经存在,MongoDB服务器会忽略该命令。如果索引不存在,MongoDB 将创建集合(如果需要)以及集合上的索引。