首页 文章

如何在数组.NET驱动程序中的项的属性上创建MongoDB MultiKey索引

提问于
浏览
9

我有一个包含项目的MongoDB集合“foos”,每个项目都有一个“bars”数组 . 也就是说,“foo”具有以下架构:

{
    "id": UUID
    "name": string
    ...
    "bars": [
        "id": UUID
        "key": string
        ...
    ]
}

我需要使用MongoDB C#.NET Mongo驱动程序在name和bar.key上创建索引 .

我假设我可以使用Linq Select函数执行此操作,如下所示:

Indexes.Add(Context.Collection<FooDocument>().Indexes.CreateOne(
    Builders<FooDocument>.IndexKeys
        .Descending(x => x.Bars.Select(y => y.Key))));

但是,这会导致InvalidOperationException:

System.InvalidOperationException:'无法确定x => x.Bars.Select(y => y.Id)的序列化信息 .

The Mongo documentation on MultiKey indexes显示了如何使用简单的点表示法创建这样的索引,即

db.foos.createIndex( { "name": 1, "bars.key": 1 } )

但是the MongoDB driver documentation似乎暗示我正在使用Linq函数是正确的 .

How can I create a multikey index on my collection using the MongoDB .NET Driver, preferably using a Linq function?

3 回答

  • 6

    这似乎是requested feature for the C# driver,尽管最近没有取得任何进展 . 也就是说,有人确实在JIRA线程上提交了粗略且准备好的解决方案,所以也许这将为您完成工作 .

  • 3

    这是一个如何用C#做的例子

    var indexDefinition = Builders<FooDocument>.IndexKeys.Combine(
        Builders<FooDocument>.IndexKeys.Ascending(f => f.Key1),
        Builders<FooDocument>.IndexKeys.Ascending(f => f.Key2));
    
    await collection.Indexes.CreateOneAsync(indexDefinition);
    

    UPDATE

    关于数组中的索引,最接近我能够找到的是使用“-1”作为构建索引键的索引 . 据我所知,从github源代码是一个有效的选项,以 Build 查询 .

    var indexDefinition = Builders<FooDocument>.IndexKeys.Combine(
        Builders<FooDocument>.IndexKeys.Ascending(f => f.Key1),
        Builders<FooDocument>.IndexKeys.Ascending(f => f.Key2[-1].Key));
    
    await collection.Indexes.CreateOneAsync(indexDefinition);
    

    "-1"是side mongodb C#驱动程序中的硬编码常量,表示"$"(proof) . 所以这段代码会尝试创建索引:

    { "Key1": 1, "Key2.$.Key": 1 }
    

    这对于从数据库查询信息很好,但不允许(将抛出异常“索引键包含非法字段名称:字段名称以'$'开头”)以在索引中使用 . 所以我认为应该在mongodb驱动程序中进行更改以使其正常工作 . 像“-2”这样的东西意味着空操作符 . 在那种情况下我们可以使用

    var indexDefinition = Builders<FooDocument>.IndexKeys.Combine(
        Builders<FooDocument>.IndexKeys.Ascending(f => f.Key1),
        Builders<FooDocument>.IndexKeys.Ascending(f => f.Key2[-2].Key));
    
    await collection.Indexes.CreateOneAsync(indexDefinition);
    

    这会生成如下索引:

    { "Key1": 1, "Key2.Key": 1 }
    

    So basically i don't think it is possible right now to build index you want with pure Linq without changing mongo C# drivers.

    所以我认为你唯一的选择就是这样,仍然是C#但没有Linq

    await collection.Indexes.CreateOneAsync(new BsonDocument {{"name", 1}, {"bars.key", 1}});
    
  • 2

    您可以创建一个字符串索引并在C#6中使用 nameof()

    Indexes.Add(Context.Collection<FooDocument>().Indexes.CreateOne($"{nameof(FooDocument.Bars)}.{nameof(Bars.Key)}"));
    

相关问题