【问题标题】:MongoDb C# Creating Index and Collection dynamiacllyMongoDb C# 动态创建索引和集合
【发布时间】:2018-03-06 11:22:03
【问题描述】:

我正在使用 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】:

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

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

    【讨论】:

    • 每次我用 CreateOne 调用数据库插入新文档时,它会重新创建索引吗?
    • IndexExistsByName 似乎与最新的 .net Mongo.db 驱动程序 2.9.2 不存在。根据stackoverflow.com/questions/35019313/…,它是幂等的,所以没有必要检查索引是否已经存在。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多