[英]How can I create a Mongo index definition from an existing one using the C# driver?
I am trying to recreate indexes from one collection for another. 我正在尝试从一个集合为另一个创建索引。
I can get the existing index from the source collection by: 我可以通过以下方式从源集合中获取现有索引:
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();
But I cannot figure out where to go from there. 但是我不知道从那里去哪里。
It becomes a bit cumbersome if you want to run strongly typed .NET driver API like targetCollection.Indexes.CreateOne()
since it requires options to be specified as CreateIndexOptions
type which expectes all the options like Sparse
or Unique
to be specified in a strongly typed way. 如果您要运行诸如targetCollection.Indexes.CreateOne()
类的强类型.NET驱动程序API,它将变得有些麻烦,因为它要求将选项指定为CreateIndexOptions
类型,从而期望在强类型中指定所有Sparse
或Unique
选项方式。
Alternatively you can create multiple indexes using createIndexes database command. 或者,您可以使用createIndexes数据库命令创建多个索引。 To run it from C# you can remove ns
from obtained BsonDocuments
since the namespace will be different and then pass all your definitions to that command. 要从C#运行它,您可以从获得的BsonDocuments
删除ns
,因为名称空间会有所不同,然后将所有定义传递给该命令。 Try: 尝试:
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)
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.