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

问题描述 投票:4回答:1

我正在使用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<BsonDocument>.IndexKeys.Ascending("datetime");
        string collectionName = collectoinName;
        database.GetCollection<BsonDocument>(collectionName).Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true});

        //Create Collection
        var dbcollection = database.GetCollection<BsonDocument>(collectionName);

        var document = new BsonDocument
                {
                    { "_id", ObjectId.GenerateNewId()},
                    { "Key1", value1 },
                    { "Key2", value2},
                    { "datetime", DateTime.Now }
                };

        dbcollection.InsertOne(document);
    }
c# mongodb
1个回答
2
投票

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

var collection = database.GetCollection<BsonDocument>(collectionName);

if (! collection.IndexExistsByName("myindex")) {
  collection.Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true});
}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.