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

标签 c# mongodb linq indexing mongodb-.net-driver

我有一个 MongoDB 集合“foos”,其中包含项目,每个项目都有一个“条”数组。也就是说,“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: 'Unable to determine the serialization information for 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 函数是正确的。

如何使用 MongoDB .NET 驱动程序在我的集合上创建多键索引,最好使用 Linq 函数?

最佳答案

这是一个使用 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); 

更新

关于数组中的索引,我能找到的最接近的是在构建索引键时使用“-1”作为索引。正如我从 github 源代码中了解到的那样,在构建查询的情况下是一个有效的选择。

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"是 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 }

所以基本上我认为现在不可能在不更改 mongo C# 驱动程序的情况下使用纯 Linq 构建您想要的索引。

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

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

关于c# - 如何在数组.NET驱动程序中的项目属性上创建MongoDB MultiKey索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44070496/

相关文章:

mongodb - Docker 中的 Mongo ReplicaSet - 无法添加用户 : not master

node.js - 尝试通过 mongoose 使用 Node js 将对象保存在文档上时出现问题

c# - LINQ 和 ExcelQueryFactory

c# - 如何处理 404 错误

MongoDB $match by 数组子集

c# - 如何使用 GraphDiff 更新表达式树

c# - xml到linq与两个类c#

c# - 如何使用 LINQ 简化代码

c# - Picturebox 中的图像 C#

c# - 覆盖等于并与字符串进行比较