在c#中创建复合索引

use*_*435 12 .net c# mongodb compound-index mongodb-.net-driver

我想创建一个复合索引,其中一个键应该是升序,第二个键是降序.

我怎样才能做到这一点?

我有一个包含用户选择的属性名称的字符串.

collection.EnsureIndex(IndexKeys.Descending(selectedProperties[0]),
                IndexKeys.Ascending(selectedProperties[1])),
IndexOptions.......
Run Code Online (Sandbox Code Playgroud)

不起作用

Wir*_*rie 11

这是一种方式:

var keys = new IndexKeysBuilder();

keys.Ascending(keyName1);
keys.Descending(keyName2);

var options = new IndexOptionsBuilder();
options.SetSparse(true);
options.SetUnique(false);
collection.EnsureIndex(keys, options);
Run Code Online (Sandbox Code Playgroud)


i3a*_*non 10

在驱动程序的v2.x中,他们完全更改了API,因此目前异步创建复合索引的方式(首选)是:

await collection.Indexes.CreateOneAsync(
    Builders<Hamster>.IndexKeys.Ascending(_ => _.Name).Descending(_ => _.Age),
    new CreateIndexOptions { Background = true });
Run Code Online (Sandbox Code Playgroud)

并同步:

collection.Indexes.CreateOne(
    Builders<Hamster>.IndexKeys.Ascending(_ => _.Name).Descending(_ => _.Age),
    new CreateIndexOptions { Sparse = true });
Run Code Online (Sandbox Code Playgroud)


i3a*_*non 6

EnsureIndex现在已经过时了,所以CreateIndex应该使用它.还有一些静态构建器类支持流畅的用法:IndexKeysIndexOptions.

所以最干净的选择是:

collection.CreateIndex(
    IndexKeys.Ascending(keyName1).Descending(keyName2),
    IndexOptions.SetSparse(true).SetUnique(false));
Run Code Online (Sandbox Code Playgroud)

对于通用的类型安全选项:

collection.CreateIndex(
    IndexKeys<Document>.Ascending(d => d.Property1).Descending(d => d.Property2),
    IndexOptions.SetSparse(true).SetUnique(false));
Run Code Online (Sandbox Code Playgroud)