假設我有一個有序的(按$sort聚合管道階段)檔案串列:
{ x: 0 }
{ x: 1 }
{ x: 3 }
{ x: 4 }
{ x: 5 }
{ x: 6 }
現在我可以選擇x >= 3使用聚合管道階段的所有檔案:
{ $match: { x: { $gte: 3 } } }
但是是否也可以匹配單個查詢x >= 3中第一個匹配元素之前的第一個元素和第一個元素的所有檔案?
預期結果是:
{ x: 1 }
{ x: 3 }
{ x: 4 }
{ x: 5 }
{ x: 6 }
(我需要這個來進行符合中繼的分頁)
uj5u.com熱心網友回復:
您可以使用$facet分成 2 個管道進行處理。然后使用$setUnion將結果重新組合回來。
db.collection.aggregate([
{
"$facet": {
"smaller": [
{
"$match": {
x: {
$lt: 3
}
}
},
{
$sort: {
x: -1
}
},
{
"$limit": 1
}
],
"larger": [
{
"$match": {
x: {
$gte: 3
}
}
}
]
}
},
// cosmetics to revert back to original form
{
"$project": {
final: {
"$setUnion": [
"$smaller",
"$larger"
]
}
}
},
{
"$unwind": "$final"
},
{
"$replaceRoot": {
"newRoot": "$final"
}
}
])
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462444.html
上一篇:基于欄位是否存在的分桶
