【问题标题】:join object from another documnt with localfield key使用 localfield 键从另一个文档连接对象
【发布时间】: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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2015-03-30
    • 2022-01-25
    • 2022-01-24
    • 2022-11-19
    • 2014-02-04
    • 2021-01-11
    相关资源
    最近更新 更多