Reputation: 175
I want to remove index using MongoDB .NET Driver (v.2.11). The issue is that I don't want to use index name, instead I would like to remove it like in: https://docs.mongodb.com/manual/tutorial/manage-indexes/ Remove Specific Index section - providing index schema. How can it be done? Now using of:
MyCollection.Indexes.DropOne("{ _id: 1, somefield: 1 }");
results in:
MongoDB.Driver.MongoCommandException: 'Command dropIndexes failed: index not found with name [{ _id: 1, somefield: 1 }].'
Note: Index exists in collection.
Upvotes: 0
Views: 1289
Reputation: 14436
There is no way currently in the C# Driver to drop an index based on its keys.
You could however search for the index and get the name and then drop the index like the following.
var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<Person>("people");
// Create a index
var keys = Builders<Person>.IndexKeys.Ascending(x => x.Surname);
await collection.Indexes.CreateOneAsync(new CreateIndexModel<Person>(keys));
var cursor = await collection.Indexes.ListAsync();
// Find the index
var indexKeys = BsonDocument.Parse("{ Surname: 1 }");
var indexName = (await cursor.ToListAsync())
.Where(x => x["key"] == indexKeys)
.Select(x => x["name"])
.Single();
// Drop index by name
await collection.Indexes.DropOneAsync(indexName.AsString);
Upvotes: 1
Reputation: 14520
The dropIndex command supports giving the index specification. You can invoke it using your driver's helper for executing arbitrary commands, if your driver does not provide a dropIndex helper that takes an index specification.
MyCollection.Indexes.DropOne("{ _id: 1, somefield: 1 }");
You tried to drop an index with the name of "{ _id: 1, somefield: 1 }"
. At a minimum you should be using the correct syntax for maps in your programming language.
Upvotes: 0