1

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.

1 Answer 1

2

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)
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me by minutes. Excellent answer, I came to the same conclusion. You can do it partially strong typed using the legacy driver however that won't support any options.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.