【问题标题】:How to remove index without knowing its name?如何在不知道其名称的情况下删除索引?
【发布时间】:2021-01-05 12:37:49
【问题描述】:

我想使用 MongoDB .NET 驱动程序 (v.2.11) 删除索引。问题是我不想使用索引名称,而是想将其删除,如下所示:https://docs.mongodb.com/manual/tutorial/manage-indexes/ Remove Specific Index 部分 - 提供索引架构。 如何做呢? 现在使用:

MyCollection.Indexes.DropOne("{ _id: 1, somefield: 1 }");

结果:

MongoDB.Driver.MongoCommandException: 'Command dropIndexes failed: index not found with name [{ _id: 1, somefield: 1 }].'

注意: 集合中存在索引。

【问题讨论】:

  • 我认为这是不可能的。不确定确切的用例,但您可以遍历索引,找到您所追求的,然后按名称删除它?

标签: c# .net mongodb indexing


【解决方案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);

【讨论】:

    【解决方案2】:

    dropIndex command 支持给出索引规范。如果您的驱动程序不提供采用索引规范的 dropIndex 帮助程序,您可以使用驱动程序的帮助程序调用它来执行任意命令。

    MyCollection.Indexes.DropOne("{ _id: 1, somefield: 1 }");

    您试图删除名称为 "{ _id: 1, somefield: 1 }" 的索引。至少您应该在您的编程语言中使用正确的映射语法。

    【讨论】:

    • 我知道 C# 驱动程序是这样工作的,因为我正在寻找一些解决方案:)
    猜你喜欢
    • 2013-08-06
    • 2010-11-23
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2010-11-28
    • 2023-03-10
    • 1970-01-01
    • 2015-03-22
    相关资源
    最近更新 更多