如何在升序 MongoDB 中最后对空值进行排序

How to sort null value at the end while in Ascending MongoDB

我有多个文档,其中一些文档不包含我要排序的那个键,因此它被视为 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 不包含排名字段,它输出最后的响应。 预期输出:

[
   {
      "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
    }
  }
])

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

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

这里是Mongo playground供您参考。