首页 > 解决方案 > 复制集合索引 c# mongo

问题描述

每个月我都需要更新我的 mongo 集合,我删除我的旧集合,然后在同一个数据库中手动创建具有相同索引的集合。然后我运行一个程序,将 txt 文件中的信息插入到集合中。我这样做的原因是因为集合很大,删除所有文档需要太多时间,删除它们要快得多。

由于有许多具有不同索引的集合,我希望以编程方式执行此操作。有没有办法在 C# 中以编程方式执行此操作?

  1. 将集合中的索引复制到列表中
  2. 丢弃集合
  3. 使用列表中的索引和相同的名称创建集合

其中一些集合具有 2DSPHERE 索引。

到目前为止,这是我的代码,但我陷入了从列表中创建索引的最后一部分:

//connecting to mongo
MongoClient client = new MongoClient("mongodb://" + MongoUser + ":" + MongoPass + "@" + MongoURL);    
IMongoCollection<BsonDocument> myCollection = client.GetDatabase("DatabaseName").GetCollection<BsonDocument>("CollectionName");

//Save indexes into a list before drop
List<BsonDocument> indexList = myCollection.Indexes.List().ToList();

//Drop and recreate         
client.GetDatabase("DatabaseName").DropCollection("CollectionName")
client.GetDatabase("DatabaseName").CreateCollection("CollectionName");

// Get new created collection
myCollection = client.GetDatabase("DatabaseName").GetCollection<BsonDocument>("CollectionName");

foreach (BsonDocument doc in indexList )
{
   //Not working
    myCollection.Indexes.CreateOne(doc);
}

标签: c#mongodbindexing

解决方案


推荐阅读