使用來自查詢同一集合的任意數量的過濾條件進行查詢
我指的是上面的問題。
這是一個額外的要求:
表score已分片。因此,它不能再在$lookup舞臺上。
是否有另一種解決方案也只訪問 MongoDB API 一次?
uj5u.com熱心網友回復:
一種無需查找的方法是使用$group,例如:
db.score.aggregate([
{
$group: {
_id: "$test_id",
highestScore: {$max: "$score"},
results: {
$push: {score: "$score", "tester_id": "$tester_id"}
},
ourTester: {
$push: {score: "$score", "tester_id": "$tester_id"}
}
}
},
{$match: {"ourTester.tester_id": userId}},
{
$project: {
ourTester: {
$filter: {
input: "$ourTester",
as: "item",
cond: {$eq: ["$$item.tester_id", userId]}
}
},
results: {
$filter: {
input: "$results",
as: "item",
cond: {$eq: ["$$item.score", "$highestScore"]}}
}
}
},
{
$project: {
ourTester: {"$arrayElemAt": ["$ourTester", 0]},
highest: {"$arrayElemAt": ["$results", 0]}
}
},
{
$match: {
$expr: {$gt: ["$highest.score", "$ourTester.score"]}
}
},
{
$project: {
score: "$highest.score",
tester_id: "$highest.tester_id",
test_id: "$res._id"
}
}
])
正如你在這里看到的
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462451.html
標籤:mongodb mongodb查询 聚合框架 mongodb-索引
