MaYaN
MaYaN

Reputation: 6986

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.

Upvotes: 1

Views: 432

Answers (1)

mickl
mickl

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

Related Questions