【发布时间】: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);
}
【问题讨论】: