skip to Main Content

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


  1. // no method to check the existence of an Index
    

    that’s not true, there is a method List that shows indexes for the current collection.

    Login or Signup to reply.
  2. 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.

    _collection.Indexes.CreateOne("{ title : 1 }");
    

    You can still check the details of the index by following code:

    var indexList = _collection.Indexes.List().ToList< BsonDocument>();
    
    indexList.ForEach(ix => Console.WriteLine(ix));`
    
    Login or Signup to reply.
  3. I created an extension method for IMongoCollection to check, wether an index for a given name already exists in that collection:

    public static bool HasIndex<T>(this IMongoCollection<T> mongoCollection, string indexName)
    {
        var indexes = mongoCollection.Indexes.List().ToList();
        var indexNames = indexes
            .SelectMany(i => i.Elements)
            .Where(e => string.Equals(e.Name, "name", StringComparison.CurrentCultureIgnoreCase))
            .Select(n => n.Value.ToString()).ToList();
    
        return indexNames.Contains(indexName);
    }
    

    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:

    var database = _mongoClient.GetDatabase("Database");
    var examples = database.GetCollection<Example>("Examples");
    
    var hasIndex = examples.HasIndex("ExampleIndex");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search