我想使用MongoDB .NET驱动程序(v.2.11)删除索引。问题是我不想使用索引名称,而是想在以下位置将其删除:https://docs.mongodb.com/manual/tutorial/manage-indexes/ 删除特定索引部分-提供索引架构。 怎么做到呢? 现在使用:
MyCollection.Indexes.DropOne("{ _id: 1, somefield: 1 }");
导致:
MongoDB.Driver.MongoCommandException: 'Command dropIndexes failed: index not found with name [{ _id: 1, somefield: 1 }].'
注意: 索引存在于集合中。
答案 0 :(得分:1)
C#驱动程序当前无法基于其键删除索引。
但是,您可以搜索索引并获取名称,然后像下面一样删除索引。
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);
答案 1 :(得分:0)
dropIndex command支持给出索引规范。如果您的驱动程序没有提供采用索引规范的dropIndex帮助程序,则可以使用驱动程序的帮助程序来调用它以执行任意命令。
MyCollection.Indexes.DropOne(“ {_id:1,somefield:1}”);
您试图删除名称为"{ _id: 1, somefield: 1 }"
的索引。至少,您应该使用编程语言为地图使用正确的语法。