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



我有两个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,其中cardType=";卡片";,完整卡对象和secondCollection中itemId所在的所有项(从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

最新更新