MongoDB

Create Indexes using C# and MongoDB

The IMongoIndexManager.CreateOneAsync method is used to create an index on a collection. MongoDB automatically creates an index on the _id field upon the creation of a collection.

Follow the Install and Connect to MongoDB step to connect to a running MongoDB instance.

 using System;  
 using System.Threading.Tasks;  
 using MongoDB.Bson;  
 using MongoDB.Driver;  
   
 namespace MongoDB  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       CreateIndex(args).Wait();  
       Console.WriteLine("Press Enter");  
       Console.ReadLine();  
     }  
     static async Task CreateIndex(string[] args)  
     {  
       var _connectionString = "mongodb://localhost:27017";  
       var _client = new MongoClient(_connectionString);  
       var _database = _client.GetDatabase("blog");  
       var _collection = _database.GetCollection("users");  
   
       //Create a Single-Field Index  
       var _key = Builders.IndexKeys.Ascending("Email");  
       await _collection.Indexes.CreateOneAsync(_key);  
   
       //Creating a Compound Index  
       var _keys = Builders.IndexKeys.Ascending("Name").Ascending("Zipcode");  
       await _collection.Indexes.CreateOneAsync(_keys);  
     }  
   }  
 }  
   

Leave a comment