Home > other >  How to create a text index in MongoDb using MongoDb driver if it is not exist
How to create a text index in MongoDb using MongoDb driver if it is not exist

Time:12-18

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
}

CodePudding user response:

// 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.

CodePudding user response:

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));`

  • Related