【发布时间】:2021-07-09 01:15:23
【问题描述】:
我有一个竞赛文档,其中包含包含团队 _id 的对象数组和包含 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"
}
]
}
我应该怎么做我已经阅读了这似乎是这样的文档?
【问题讨论】:
-
请添加您的示例数据
标签: javascript node.js mongodb mongoose aggregation-framework