如何使用 C# 驱动程序从现有索引定义创建 Mongo 索引定义?
How can I create a Mongo index definition from an existing one using the C# driver?
我正在尝试从一个集合中为另一个集合重新创建索引。
我可以通过以下方式从源集合中获取现有索引:
var sourceCollectionName = "source";
var targetCollectionName = "target";
var sourceCollection = db.GetCollection<BsonDocument>(sourceCollectionName);
var targetCollection = db.GetCollection<BsonDocument>(targetCollectionName);
List<BsonDocument> sourceCollectionIndexes = await(await sourceCollection.Indexes.ListAsync()).ToListAsync();
但我不知道从那里去哪里。
如果你想 运行 强类型的 .NET 驱动程序 API 像 targetCollection.Indexes.CreateOne()
会变得有点麻烦,因为它需要将选项指定为 CreateIndexOptions
类型期望以强类型方式指定所有选项,如 Sparse
或 Unique
。
或者您可以使用 createIndexes 数据库命令创建多个索引。要从 C# 运行 它,您可以从获得的 BsonDocuments
中删除 ns
,因为命名空间将不同,然后将所有定义传递给该命令。尝试:
var sourceCollectionName = "source";
var targetCollectionName = "target";
var sourceCollection = Db.GetCollection<BsonDocument>(sourceCollectionName);
List<BsonDocument> sourceCollectionIndexes = await (await sourceCollection.Indexes.ListAsync()).ToListAsync();
foreach(var indexDef in sourceCollectionIndexes)
{
indexDef.Remove("ns");
}
await Db.RunCommandAsync<BsonDocument>(new BsonDocument()
{
{ "createIndexes", targetCollectionName },
{
"indexes", new BsonArray(sourceCollectionIndexes)
}
});
我正在尝试从一个集合中为另一个集合重新创建索引。
我可以通过以下方式从源集合中获取现有索引:
var sourceCollectionName = "source";
var targetCollectionName = "target";
var sourceCollection = db.GetCollection<BsonDocument>(sourceCollectionName);
var targetCollection = db.GetCollection<BsonDocument>(targetCollectionName);
List<BsonDocument> sourceCollectionIndexes = await(await sourceCollection.Indexes.ListAsync()).ToListAsync();
但我不知道从那里去哪里。
如果你想 运行 强类型的 .NET 驱动程序 API 像 targetCollection.Indexes.CreateOne()
会变得有点麻烦,因为它需要将选项指定为 CreateIndexOptions
类型期望以强类型方式指定所有选项,如 Sparse
或 Unique
。
或者您可以使用 createIndexes 数据库命令创建多个索引。要从 C# 运行 它,您可以从获得的 BsonDocuments
中删除 ns
,因为命名空间将不同,然后将所有定义传递给该命令。尝试:
var sourceCollectionName = "source";
var targetCollectionName = "target";
var sourceCollection = Db.GetCollection<BsonDocument>(sourceCollectionName);
List<BsonDocument> sourceCollectionIndexes = await (await sourceCollection.Indexes.ListAsync()).ToListAsync();
foreach(var indexDef in sourceCollectionIndexes)
{
indexDef.Remove("ns");
}
await Db.RunCommandAsync<BsonDocument>(new BsonDocument()
{
{ "createIndexes", targetCollectionName },
{
"indexes", new BsonArray(sourceCollectionIndexes)
}
});