I've had the same problem while using the mongo c# driver (v2.2.3) and saw Alkampfer
's answer.
in version 2.2.3, indexes are managed through the collection's Indexes
property.
I've written an extension method for the indexes property based on Alkampfer's
answer as follows:
public static async Task AddOrUpdateAsync<TDocument>(this IMongoIndexManager<TDocument> indexes, CreateIndexOptions options, IndexKeysDefinition<TDocument> keys = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (keys == null)
{
keys = Builders<TDocument>.IndexKeys.Ascending(options.Name);
}
try
{
await indexes.CreateOneAsync(keys, options, cancellationToken).ConfigureAwait(false);
}
catch (MongoCommandException e)
{
await indexes.DropOneAsync(options.Name, cancellationToken).ConfigureAwait(false);
await AddOrUpdateAsync(indexes, options, keys, cancellationToken).ConfigureAwait(false);
}
}
Although it's a little dirty (catching exceptions and retrying is not best practice) it's the simplest solution to the issue
If you are afraid for the code's Performance, you usually use the dirty part once per change to indexes(which as I recall, doesn't happen that often).
If you want there's an alternative of iterating over the collection's indexes, but it's a rather messy process (moveNexts and accessing current position)