【问题标题】:MongoDB C# Sort null values lastMongoDB C#最后对空值进行排序
【发布时间】:2021-12-24 21:36:31
【问题描述】:

我正在使用 Mongo C# 驱动程序来过滤数据表。 location(城市字符串)字段可以为空,升序排序时,位置为空的结果在前。我想先对任何有位置的东西进行排序,然后将那些没有位置(null)的东西放在列表的末尾,所以当按升序排序时,列表总是从位置 A-Z 开始。过滤器非常复杂,因此它使用过滤器构建器并在此处进行排序。

有人知道使用 C# Mongo 库告诉排序将空值放在排序末尾的方法吗?我正在使用最新版本的库。我已经尝试了各种方法:投影并将结果合并为 null(不支持),但似乎没有任何效果。

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

我在 Google 上搜索了很长时间,但似乎找不到任何做过的人。

任何帮助表示赞赏。

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)                });

【问题讨论】:

    标签: c# mongodb sorting


    【解决方案1】:

    试试这个:

    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)                
    });
    

    【讨论】:

    • 你测试过这个吗?
    • Alas Linq 不允许合并
    猜你喜欢
    • 2021-12-11
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-02
    相关资源
    最近更新 更多