この質問とほぼ同じ$match
ように、集計内のステージのクエリを探していますが、..
$operator
場合は、$max
このフィールドに条件(私の場合は)を適用し、この条件に適合するすべてのドキュメントを結果に追加します。結果は次のようになります。
[
{
"method": 3,
"item": 1,
"rank": 3 //because it has field named rank, and suits condition {rank: $max}
},
{
"method": 4,
"item": 1 //we need this, because document doesn't have rank field at all
},
{
"method": 5,
"item": 1 //we need this, because document doesn't have rank field at all
}
]
私がすでに試したこと:
{
$match: {
$or: [
{item: id, rank: {$exists: true, $max: "$rank"}}, //id === 1
{item: id, rank: {$exists: false}} //id === 1
]
}
}
UPD:今のところ、おそらく
$match
ステージだけに限定するので$project
はなく、デフォルトの一致後にも関連するので、$match
ステージ中にすべてのドキュメントをリクエストできid
ます。ドキュメントrank
フィールドがあるかどうかに関係なく、$project
ステージ中に「ランク別の分離」$exists
これを試してください:
db.collection.aggregate([
{
$match: {
item: id
}
},
{
$group: {
_id: "$item", //<- Change here your searching field
max: {
$max: "$rank" //<- Change here your field to apply $max
},
data: {
$push: "$$ROOT"
}
}
},
{
$unwind: "$data"
},
{
$match: {
$expr: {
$or: [
{
$eq: [
{
$type: "$data.rank"
},
"missing"
]
},
{
$eq: [
"$data.rank",
"$max"
]
}
]
}
}
},
{
$replaceWith: "$data"
}
])
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加