【问题标题】:How to sort null value at the end while in Ascending MongoDB如何在升序 MongoDB 中最后对空值进行排序
【发布时间】:2021-12-11 18:28:47
【问题描述】:

我有多个文档,其中一些文档不包含我要排序的那个键,因此它被视为 null,当我排序时,首先出现的是 null 数据,但我需要优先考虑其他一个并且 null 放置在结尾。 样本数据:

[
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":"A",
      "description":"Mens Upper Shirt"
   },
   {
      "cat_id":2,
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_type":"A",
      "rank":5,
      "description":"Shirt"
   },
   {
      "cat_id":3,
      "categoryCode":"categoryCode3",
      "categoryName":"categoryName3",
      "cat_type":"Women Top wear",
      "description":"cloths"
   },
   {
      "cat_id":4,
      "categoryCode":"categoryCode4",
      "categoryName":"categoryName4",
      "cat_type":"A",
      "rank":8,
      "description":"Women"
   }
]

在上面的例子中 cat_id- 1 和 3 不包含 rank 字段并且它输出它最后来的响应。 预期输出:

[
   {
      "cat_id":2,
      "categoryCode":"categoryCode2",
      "categoryName":"categoryName2",
      "cat_type":"A",
      "rank":5,
      "description":"Shirt"
   },
   {
      "cat_id":4,
      "categoryCode":"categoryCode4",
      "categoryName":"categoryName4",
      "cat_type":"A",
      "rank":8,
      "description":"Women"
   },
   {
      "cat_id":1,
      "categoryCode":"categoryCode1",
      "categoryName":"categoryName1",
      "cat_type":"A",
      "description":"Mens Upper Shirt"
   },
   {
      "cat_id":3,
      "categoryCode":"categoryCode3",
      "categoryName":"categoryName3",
      "cat_type":"Women Top wear",
      "description":"cloths"
   }
]

我正在使用这个查询-

db.collection.aggregate([
  {
    $addFields: {
      sortrank: {
        $cond: {
          if: {
            $eq: [
              "$rank",
              null
            ]
          },
          then: 2,
          else: 1
        }
      }
    }
  },
  {
    "$sort": {
      "sortrank": 1
    }
  }
])

【问题讨论】:

  • 我认为这不能在数据库内部完成。见MongoDB Comparison/Sort Order
  • 是的@ray 我正在寻找相同类型的输出。基本上,您在发现 null 的地方添加了更高的静态值,然后排序正常工作,对吗?

标签: mongodb mongoose mongodb-query spring-data aggregation-framework


【解决方案1】:

我认为您使用辅助字段进行排序的方向是正确的。您可以使用$ifNull 指定一个密集索引(例如 999)作为您的排序等级。

db.collection.aggregate([
  {
    "$addFields": {
      "sortrank": {
        "$ifNull": [
          "$rank",
          999
        ]
      }
    }
  },
  {
    $sort: {
      sortrank: 1
    }
  },
  {
    $project: {
      sortrank: false
    }
  }
])

这里是Mongo playground 供您参考。

【讨论】:

  • 是的,它正在工作,但我不能用 999 分配静态排名,因为如果任何其他数据超过 999,那么最后不会打印空值,而不是 999 我将使用boolean true,因为 boolean 具有比 Number 更高的比较索引。然后它总是在最后打印。
  • 999 只是密集排序等级的一个示例。但我认为你很聪明,已经明白了:)
猜你喜欢
  • 2021-12-24
  • 2017-04-30
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 2021-06-10
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
相关资源
最近更新 更多