Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo create_index only if it does not exist

In a Python script using PyMongo, an index is created for a collection using the line

myCollection.create_index('Datetime', unique=True)

However this throws an error the next time the script is executed because the index already exist.

Question: Is there a way to check for the existance of an index before deciding whether to call create_index?

like image 242
Nyxynyx Avatar asked Apr 29 '16 13:04

Nyxynyx


1 Answers

In PyMongo 3.6.0 and later, calling create_index will not recreate the index if it already exists and will not throw an error. The index creation will just be ignored if the index already exists.

like image 199
Victor Deplasse Avatar answered Nov 04 '22 00:11

Victor Deplasse