我有多個檔案,其中一些檔案不包含我想要排序的鍵,因此它被視為空值,當我排序時,空資料首先出現,但我需要優先選擇另一個,并將空值放在最后。樣本資料:
[
{
"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
}
}
])
uj5u.com熱心網友回復:
我認為您使用輔助欄位進行排序的方向是正確的。您可以使用$ifNull指定一個密集索引(例如 999)作為您的排序等級。
db.collection.aggregate([
{
"$addFields": {
"sortrank": {
"$ifNull": [
"$rank",
999
]
}
}
},
{
$sort: {
sortrank: 1
}
},
{
$project: {
sortrank: false
}
}
])
這是Mongo 游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339370.html
標籤:mongodb 猫鼬 mongodb-查询 弹簧数据 聚合框架
上一篇:如何以PythonPandas資料幀表格式獲取mongodb嵌套檔案
下一篇:從refobjectid查詢
