如何排序空值在最后,而在上升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 and 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
}
}
])

我认为您使用辅助字段排序的方向是正确的。您可以使用$ifNull来分配密集索引(例如:999)作为你的排序等级。

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

这是Mongo游乐场供您参考。

最新更新