3

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)   
Dims
  • 47,675
  • 117
  • 331
  • 600

1 Answers1

5

As you see, calling index_information on a collection that doesn't exist yet throws OperationFailure.

Just call create_index without checking first:

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)

If the index already exists, the MongoDB server ignores the command. If the index does not exist, MongoDB creates the collection (if necessary) and the index on the collection.

A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70