MongoDb C#动态创建索引和集合

我正在使用C#(MongDB驱动程序)动态创建集合。 我发现只有在插入至少一个文档时才会创建集合。 我正在做如下。 由于我为每个插入创建索引调用CreatOne,每次插入新文档时它会重新创建索引吗? 有没有更好的方法来动态创建集合和索引?

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.IndexKeys.Ascending("datetime"); string collectionName = collectoinName; database.GetCollection(collectionName).Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true}); //Create Collection var dbcollection = database.GetCollection(collectionName); var document = new BsonDocument { { "_id", ObjectId.GenerateNewId()}, { "Key1", value1 }, { "Key2", value2}, { "datetime", DateTime.Now } }; dbcollection.InsertOne(document); } 

在创建索引之前,您可以先检查索引是否存在。 API提供了一个方法IndexExistsByName来检查索引是否存在。

 var collection = database.GetCollection(collectionName); if (! collection.IndexExistsByName("myindex")) { collection.Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true}); }