使用 localfield 键连接另一个文档中的对象

时间:2021-04-14 00:48:36

标签: javascript node.js mongodb mongoose aggregation-framework

我有一个竞赛文档,其中包含带有团队 _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"
      }
    }
  }
])

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

{ 
    "_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"
        }
    ]
}

我应该怎么做我已经阅读了文档,这似乎是这样?

1 个答案:

答案 0 :(得分:1)

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

您必须添加 $unwind: { "path": "$comp.teams" } 在那个小组之后 { $group: { "_id": "$comp.teams._id" ... }

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

相关问题