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

7

我正在使用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);
    }
2个回答

3

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

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

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

1
每次我在数据库上调用CreateOne插入新文档时,它会重新创建索引吗? - Vaibhav shetty
4
最新的.NET Mongo.db驱动程序2.9.2中貌似没有IndexExistsByName函数。根据https://dev59.com/JFsW5IYBdhLWcg3wZmmc的说法,该函数是幂等的,因此无需检查索引是否已存在。 - Markus

0
截至2021年11月,即使您未插入值,您的代码仍能正常运行。我正在使用版本为2.13.2的MongoDB.Driver。
public static void CreateCollection(string collectoinName)
    {
        var connectionString = "mongodb://SERVER_ADDRESS:PORT";
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("test");

        //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 });

        
    }

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接