我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)
在创建索引之前,您可以先检查索引是否存在。API 提供了IndexExistsByName方法来检查索引是否存在。
var collection = database.GetCollection<BsonDocument>(collectionName);
if (! collection.IndexExistsByName("myindex")) {
collection.Indexes.CreateOne(indexDefn, new CreateIndexOptions() { Background = true, Sparse = true});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1891 次 |
| 最近记录: |