Iva*_*van 12 c# linq indexing mongodb mongodb-.net-driver
我有一个包含项目的MongoDB集合"foos",每个项目都有一个"bars"数组.也就是说,"foo"具有以下架构:
{
"id": UUID
"name": string
...
"bars": [
"id": UUID
"key": string
...
]
}
Run Code Online (Sandbox Code Playgroud)
我需要使用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))));
Run Code Online (Sandbox Code Playgroud)
但是,这会导致InvalidOperationException:
System.InvalidOperationException:'无法确定x => x.Bars.Select(y => y.Id)的序列化信息.
关于MultiKey索引的Mongo文档显示了如何使用简单的点表示法创建这样的索引,即
db.foos.createIndex( { "name": 1, "bars.key": 1 } )
Run Code Online (Sandbox Code Playgroud)
但是,MongoDB驱动程序文档似乎表明我正在使用Linq函数是正确的.
如何使用MongoDB .NET驱动程序在我的集合上创建多键索引,最好使用Linq函数?
Art*_*yom 12
这是一个如何用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);
Run Code Online (Sandbox Code Playgroud)
UPDATE
关于数组中的索引,最接近我能够找到的是使用"-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);
Run Code Online (Sandbox Code Playgroud)
"-1"是侧面mongodb C#驱动程序中的硬编码常量,表示"$"(证明).所以这段代码会尝试创建索引:
{ "Key1": 1, "Key2.$.Key": 1 }
Run Code Online (Sandbox Code Playgroud)
这对于从数据库查询信息很好,但不允许(将抛出异常"索引键包含非法字段名称:字段名称以'$'开头")以在索引中使用.所以我认为应该在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);
Run Code Online (Sandbox Code Playgroud)
这将生成如下索引:
{ "Key1": 1, "Key2.Key": 1 }
Run Code Online (Sandbox Code Playgroud)
所以基本上我认为现在不可能在没有更改mongo C#驱动程序的情况下使用纯Linq构建索引.
所以我认为你唯一的选择就是这样,仍然是C#但没有Linq
await collection.Indexes.CreateOneAsync(new BsonDocument {{"name", 1}, {"bars.key", 1}});
Run Code Online (Sandbox Code Playgroud)
您可以创建一个字符串索引并nameof()在C#6中使用:
Indexes.Add(Context.Collection<FooDocument>().Indexes.CreateOne($"{nameof(FooDocument.Bars)}.{nameof(Bars.Key)}"));
Run Code Online (Sandbox Code Playgroud)