【发布时间】: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