我需要首先$or解決(或等效查詢)的第一部分,并確保第一個查詢始終是結果的一部分。
必須使用查詢,而不是聚合。
[
{ "docId": "x1" },
{ "docId": "x2" },
{ "docId": "x3" },
{ "docId": "x4" },
{ "docId": "x5" },
...
{ "docId": "xn" },
]
詢問:
{
'$or': [ { docId: 'x434' },{} ],
}
無論所有其他結果如何,我都需要x434成為查詢結果的一部分。
預期結果:
[
{ docId: 'x434' },
{ docId: 'x12' },
{ docId: 'x1' },
...
]
回傳:
[
{ docId: 'xn' },
{ docId: 'xn' },
{ docId: 'xn' },
...
]
結果x434并不總是回傳
我嘗試$or了$and查詢,但沒有任何效果。regex我也試過
{
'$or': [ { docId: 'x434' },{} ],
}
uj5u.com熱心網友回復:
所以解決方案只能是聚合:
$match: {
'$or': [ { docId: 'x434' },{} ],
},
$addFields: {
order: {
$cond: [
{
$in: [
"$docId",
['x434']
]
},
0,
1
]
}
},
$sort: {
order: 1
},
$limit: 20
結果:
{ docId: 'x434' },
{ docId: 'x12' },
{ docId: 'x1' },
...
]```
uj5u.com熱心網友回復:
一個簡單的解決方案可以使用$facet:
db.collection.aggregate([
{$facet: {
allOther: [{$match: {docId: {$ne: "x434"}}}, {$limit: 19}],
wanted: [{$match: {docId: "x434"}}]
}},
{$project: {data: {$concatArrays: ["$wanted", "$allOther"]}}},
{$unwind: "$data"},
{$replaceRoot: {newRoot: "$data"}}
])
看看它在操場上的例子是如何作業的
uj5u.com熱心網友回復:
您可以使用$unionWith. 它的行為類似于UNION ALLSQL,因此您可以在開始時保留 x434。如果需要,請記住在管道中排除 x434$unionWith以避免重復
db.collection.aggregate([
{
$match: {
"docId": "x434"
}
},
{
"$unionWith": {
"coll": "collection",
"pipeline": [
// exclude x434 to avoid duplicate
{
$match: {
"docId": {
$ne: "x434"
}
}
}// put your other queries here
]
}
}
])
蒙戈游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/528261.html
