Reputation: 6986
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.
Upvotes: 1
Views: 432
Reputation: 49945
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.
Alternatively you can create multiple indexes using createIndexes database command. 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. 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)
}
});
Upvotes: 2