我有两个合集,一个是给在线玩家的,另一个是给有账号的玩家的。 我正在尝试查找有多少拥有帐户的玩家在线。 在 3 个匹配字段(姓氏或电子邮件或名字或手机)中出现肯定标识 我正在使用 bucketAuto 方法。代码通过
{
from: "players",
let: {
last_name: "$last_name",
email: "$email",
first_name: "$first_name",
mobile: "$mobile",
},
pipeline: [
{
$bucketAuto:
{groupBy:{
"$size": {
"$setIntersection": [
[
"$$last_name",
"$$email",
"$$first_name",
"$$mobile"
],
[
"$last_name",
"$email",
"$first_name",
"$mobile"
],
]},
},
buckets:5
}
}
],
'as': "matches",
}
#This is the model of the resulting output:
matches
0 Object
_id Object
count
5043
1 Object
_id
Object
count
4
我理解5043代表文档的所有不匹配,4是目标文档的匹配数。
我的意图是得到类似的东西:
matches
0 Object
_id 0
count
5043
1 Object
_id 1
count
1
2 Object
_id 2
count
3
3 Object
_id 3
count
0
4 Object
_id 4
count
4
组 _id 应该是 bucketAuto 阶段与其各自计数器的交集数。
Sample data:
{
"last_name": "Hansen",
"first_name": "Dawn",
"email": "[email protected]",
"mobile": "+352000900"
}
我已经表达过的期望输出说“我的意图是得到类似......”的东西
您的解决方案基本上是将一个集合中的每个文档与另一个集合中的每个文档进行比较,因此考虑到效率并根据您的目的,我建议从
$match
步骤开始管道。然后我们可以继续交集测试,但我们只对具有 3 个或更多匹配字段的文档感兴趣,并且对于每个匹配字段,只有最佳匹配是相关的:
db.online.aggregate([
{$lookup: {
from: "players",
let: {
last_name: "$last_name",
email: "$email",
first_name: "$first_name",
mobile: "$mobile"
},
pipeline: [
{$match: {$expr: {$or: [
{$eq: ["$email", "$$email"]},
{$eq: ["$mobile","$$mobile"]}
]}}},
{$project: {
_id: 0,
matchFieldsCount: {
$size: {$setIntersection: [
[
"$$last_name",
"$$email",
"$$first_name",
"$$mobile"
],
[
"$last_name",
"$email",
"$first_name",
"$mobile"
]
]}
}
}},
{$match: {matchFieldsCount: {$gte: 3}}},
{$sort: {matchFieldsCount: -1}},
{$limit: 1}
],
as: "matches"
}},
{$set: {matches: {$first: "$matches"}}},
{$bucketAuto: {groupBy: "$matches.matchFieldsCount", buckets: 3}}
])