如何使用C#驱动程序从现有的Mongo索引定义创建Mongo索引定义?

如何使用C#驱动程序从现有的Mongo索引定义创建Mongo索引定义?,c#,.net,mongodb,mongodb-.net-driver,C#,.net,Mongodb,Mongodb .net Driver,我正在尝试从一个集合为另一个集合重新创建索引 我可以通过以下方式从源集合获取现有索引: var sourceCollectionName = "source"; var targetCollectionName = "target"; var sourceCollection = db.GetCollection<BsonDocument>(sourceCollectionName); var targetCollection = db.GetCollection<BsonD

我正在尝试从一个集合为另一个集合重新创建索引

我可以通过以下方式从源集合获取现有索引:

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();
var sourceCollectionName=“source”;
var targetCollectionName=“target”;
var sourceCollection=db.GetCollection(sourceCollectionName);
var targetCollection=db.GetCollection(targetCollectionName);
List SourceCollectionIndex=await(await sourceCollection.Indexes.ListAsync()).ToListAsync();

但是我不知道从那里走到哪里。

如果您想运行像
targetCollection.index.CreateOne()这样的强类型.NET驱动程序API,那就有点麻烦了
因为它要求将选项指定为
CreateIndexOptions
类型,这要求所有选项(如
Sparse
Unique
)都以强类型方式指定

或者,您可以使用数据库命令创建多个索引。要从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(sourceCollectionName);
List SourceCollectionIndex=await(await sourceCollection.Indexes.ListAsync()).ToListAsync();
foreach(SourceCollectionIndex中的var indexDef)
{
indexDef.Remove(“ns”);
}
wait Db.RunCommandAsync(新的BsonDocument()
{
{“createIndexes”,targetCollectionName},
{
“索引”,新的BsonArray(SourceCollectionIndex)
}
});

比我快几分钟。回答得很好,我得出了同样的结论。您可以使用旧版驱动程序进行部分强类型化,但它不支持任何选项。