Note: other answers are for older versions.
version : 2.18
I am using MongoDb.Driver with C# and want to create an Index only if it does not exist.
There is no method to check the existence of an Index and I can not create Index either. All the answers and docs are very old :
protected readonly IMongoDatabase _database;
protected readonly IMongoCollection<Product> _collection;
public ProductConfiguration(IMongoDatabase mongoDatabase)
{
_database = mongoDatabase;
_collection = _database.GetCollection<Product>(typeof(Product).Name);
}
public void CreateProductIndex()
{
_collection.Indexes // no method to check the existence of an Index
}
3
Answers
that’s not true, there is a method
List
that shows indexes for the current collection.You don’t need to check if index is already created or not. If index is already created then database will ignore your new index creation request.
You can still check the details of the index by following code:
I created an extension method for IMongoCollection to check, wether an index for a given name already exists in that collection:
So whenever you want to check if an index exists in a specific collection of a mongo database you can check it via this example: