我有一个 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/