title: MongoDb C# Creating Index and Collection dynamiaclly
body: <p>I am creating a collection dynamically using C#(MongDB driver).
  I found that  collection gets created only if atleast one document is inserted into it. i am doing as below. Since i am calling CreatOne for every insert to create index, will it ReCreate index every time i insert new docs?
  Is there any better way for creating collection and index dynamically than this?</p>
  
  <pre><code>public static void CreatAndInsert(double value1, double value2, string collectoinName)
      {
          var connectionString = "mongodb://localhost";
          var client = new MongoClient(connectionString);
          var database = client.GetDatabase("sample");
  
          //Create Index
          var indexDefn = Builders&lt;BsonDocument&gt;.IndexKeys.Ascending("datetime");
          string collectionName = collectoinName;
          database.GetCollection&lt;BsonDocument&gt;(collectionName).Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true});
  
          //Create Collection
          var dbcollection = database.GetCollection&lt;BsonDocument&gt;(collectionName);
  
          var document = new BsonDocument
                  {
                      { "_id", ObjectId.GenerateNewId()},
                      { "Key1", value1 },
                      { "Key2", value2},
                      { "datetime", DateTime.Now }
                  };
  
          dbcollection.InsertOne(document);
      }
  </code></pre>