I was using automatic collection creation in pymongo:
client = MongoClient(url)
db = client.get_default_database()
my_collection = db['my_collection']
I was thinking it created automatically on last statement and added
index_name = 'my_index'
if index_name not in my_collection.index_information():
my_collection.create_index(..., name=index_name, unique=False)
Unfortunately, this led to error
pymongo.errors.OperationFailure: Collection ... doesn't exist
This made me think, that collection is created on first save. This gives me no place to put index creation code.
So, the question is: how to create collection with index, but only if it doesn't exist?
I have read this answer https://stackoverflow.com/a/9826294/258483 but don't like how it implies to write check of existence twice:
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)