MongoDB C#最后对空值进行排序



我使用Mongo C#驱动程序来过滤数据表。位置(城市的字符串(字段可以为空,当按升序排序时,位置为空的结果会排在第一位。我想先对有位置的东西进行排序,然后把没有位置的(null(放在列表的末尾,所以当按升序排序时,列表总是从位置a-Z开始。过滤器非常复杂,所以它使用了一个过滤器生成器,并在这里进行排序。

有人知道使用C#Mongo库告诉排序将null值放在排序末尾的方法吗?我用的是图书馆的最新版本。我尝试过各种方法:投影和将结果合并为null(不支持(,但似乎都不起作用。

我可以得到两组数据并将它们粘在一起,但这感觉真的很混乱,也许是我的最后手段。

我在谷歌上搜索了很长时间,似乎找不到做过这件事的人。

感谢您的帮助。

var jobsResults = await collection.FindAsync(filter, new FindOptions<MongoJob>
{
Limit = criteria?.Take,
Skip = criteria?.Skip,
Sort = criteria?.SortByDirection == "asc"
? new SortDefinitionBuilder<MongoJob>().Ascending(x => x.Location)
: new SortDefinitionBuilder<MongoJob>().Descending(x => x.Location),
Collation = new Collation("en", strength: CollationStrength.Secondary)                });

试试这个:

var jobsResults = await collection.FindAsync(filter, new FindOptions<MongoJob>
{
Limit = criteria?.Take,
Skip = criteria?.Skip,
Sort = criteria?.SortByDirection == "asc"
? new SortDefinitionBuilder<MongoJob>().Ascending(x => x.Location ?? "zzzzzz")
: new SortDefinitionBuilder<MongoJob>().Descending(x => x.Location ?? "zzzzzz"),
Collation = new Collation("en", strength: CollationStrength.Secondary)                
});

最新更新