我有一个MongoDB集合"foos",其中包含的每个项目都有一个"条"array.也就是说,"foo"具有以下模式:

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

我需要在name和bar上创建一个索引.使用MongoDB C#键.网络Mongo 司机.

我假设我可以使用Linq Select函数来完成以下操作:

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

但是,这会导致无效操作异常:

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函数是正确的.

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

推荐答案

这是一个如何用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了解,源代码是构建查询的有效选项.

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#drivers中的硬编码常量,表示"$"(proof).因此,这段代码将try 创建索引:

{ "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.

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

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

Mongodb相关问答推荐

从两个相连的文件中获取电话和邮箱的渠道是什么?

MongoDB合并按键更新值的对象数组

MongoDB对两个串联数组进行排序

在 MongoDB 中使用 findOneAndUpdate 有条件地更新/更新嵌入式数组

在mongodb中,如何使用聚合来获取字段之间的对应关系

创建索引需要很长时间

Raft Vs MongoDB 初选

使用 mgo 从 golang 中的 Mongodb 中 Select 列

Java MongoDB FindOne 获取最后插入的记录

Mongo 重启错误 -- /var/run/mongodb/mongod.pid 存在

Mongodb将重音字符匹配为基础字符

Mongo:统计一组文档中单词出现的次数

如何使用 Node.js 和 mongoose 解决command find requires authentication?

`fields cannot be identical'和''` mongoimport错误

如何在 Mongoose 中更新数组值

在 mongodb 聚合框架中执行 case-statement

Mongodb:为什么 show dbs 不显示我的数据库?

C# MongoDB 驱动程序 - 如何使用 UpdateDefinitionBuilder?

mongodb: UnknownError assertion src/mongo/db/server_options_helpers.cpp:355

RoboMongo:不显示所有文档