使用localfield键联接来自另一个文档的对象



我有一个带有field teams的竞赛文档,id为team的对象数组和一个带有teamId字段的得分文档

competitions.teams=[{_id:100,..},{..}]score.teamId=100

当汇总分数时,我想将其分组到竞争团队,但我会将所有团队都分组,而不是匹配id

样本文件https://mongoplayground.net/p/yJ34IBnnuf5

db.scores.aggregate([
{
"$match": {
"type": "league"
}
},
{
"$lookup": {
"from": "competitions",
"localField": "competitionId",
"foreignField": "_id",
"as": "comp"
}
},
{
"$unwind": {
"path": "$comp",
"preserveNullAndEmptyArrays": true
}
},
{
"$project": {
"comp.teams": 1,
"teamId": 1
}
},
{
"$group": {
"_id": "$teamId",
"results": {
"$push": "$comp.teams"
}
}
}
])

返回组中的所有团队,而不是匹配的团队ID

{ 
"_id" : 100
"results" : [
{
"_id": 100,
"name": "team 1"
},
{
"_id": 101,
"name": "team 2"
}
]
}
{ 
"_id" 101
"results" : [
{
"_id": 100,
"name": "team 1"
},
{
"_id": 101,
"name": "team 2"
}
]
}

这是我试图实现的结果,请指导我

{ 
"_id" : 100
"results" : [
{
"_id": 100,
"name": "team 1"
}
]
}
{ 
"_id" 101
"results" : [
{
"_id": 101,
"name": "team 2"
}
]
}

我该怎么办?我已经读过文档了,好像就是这样?

演示-https://mongoplayground.net/p/ETeroLftcZZ

您必须添加$unwind: { "path": "$comp.teams" }CCD_ 2

db.scores.aggregate([
{ $match: { "type": "league" } },
{ $lookup: { "from": "competitions", "localField": "competitionId", "foreignField": "_id", "as": "comp" } },
{ $unwind: { "path": "$comp",  "preserveNullAndEmptyArrays": true  } },
{ $unwind: { "path": "$comp.teams",  "preserveNullAndEmptyArrays": true }},
{ $group: { "_id": "$comp.teams._id",  "results": { $push: "$comp.teams" } } }
])

演示更多数据-https://mongoplayground.net/p/b41Ch5ge2Wp

最新更新