需要“$lookup”的替代解决方案,因为“from”字段中的集合已分片
Alternative solution to `$lookup` needed because the collection in the `from` field is sharded
我指的是上面的问题
这里有一个附加要求:
score
table 被分片。因此,它不能再处于 $lookup
阶段。
有没有另一种解决方案也只去 MongoDB API 一次?
一种无需查找的方法是使用 $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"
}
}
])
如你所见here
我指的是上面的问题
这里有一个附加要求:
score
table 被分片。因此,它不能再处于 $lookup
阶段。
有没有另一种解决方案也只去 MongoDB API 一次?
一种无需查找的方法是使用 $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"
}
}
])
如你所见here