mongodb 根据一个集合中数组的值从 2 个集合中获取记录的聚合管道解决方案

mongodb aggregation pipeline solution for getting record from 2 collections based on the value from an array in one collection

我有两个 mongoDb 集合,一个包含关于卡片的数据,另一个包含关于卡片字段和调用列表的数据。 firstCollection 的结构:

{ 
    "cardType":"card", 
    "xyz":"XYZ", 
    "fields":[ 
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "Entry", "xyz":"xyz"}, 
        {"abc":"abc", "xyz":"XYZ", "inputMethod" : "List", "xyz":"xyz", "ListId":"1234"}
        // ListId will only be present incase of inputMethod=List 
    ] 
}

secondCollection 的结构:

{ "abc":"abc", "xyz":"xyz, "itemId": "1234" }

现在我想要的是 所有 firstCollection where cardType = "card", 完整的卡片对象 和 来自 secondCollection 的所有项目,其中 itemId 在(select 来自 firstCollection 的 ListId,其中 fields.inputmethod =“List”)。

需要为这种情况编写 MongoDB 管道。我对 mongo 很陌生,可以使用带 $loopup 的聚合管道来完成,但我可以编写管道。 我想要的结果:

{
    firstCollection:{complete collection },
    secondCollection:[ 
        array of matching records from second collection where 
        secondelement.itemId in(records from array of firstcollection 
        where fields.inputmethod = "List" )
    ]
}
db.first.aggregate([
  {
    $match: {}
  },
  {
    $project: {
      firstCollection: "$$ROOT"
    }
  },
  {
    $lookup: {
      "from": "second",
      "localField": "firstCollection.fields.ListId",
      "foreignField": "itemId",
      "as": "secondCollection"
    }
  }
])

mongoplayground