链式查找聚合 mongoDB 多个集合
Posted
技术标签:
【中文标题】链式查找聚合 mongoDB 多个集合【英文标题】:Chained lookup aggregation mongoDB multiple collections 【发布时间】:2020-02-16 01:22:05 【问题描述】:大家好,我想问一下。
所以我有 3 个收藏:
-
品牌:(brandId、brandName 等...)
合作伙伴:(partnerId、partnerName 等...)
合作伙伴关系:(partnersipId、brandId、partnerId 等...)
如您所见,我想通过 partnerId 加入合作伙伴收藏,我已经加入了。但我需要brandName 成为合作收藏中的brandName 字段。我已经尝试过这个查询:
db.getCollection('partner').aggregate([
$match: partnerId: 107
,
"$lookup":
"from" : "partnership",
"localField" : "partnerId",
"foreignField" : "partnerId",
"as" : "partnership"
,
"$lookup" :
"from" : "brand",
"localField" : "partnership.brandId",
"foreignField" : "partnership.brandId",
"as" : "partnership.brand"
])
但没有运气:(
预期结果:
partnerId: 107,
partnerName: 'TEST',
partnership: [
partnerId: 107,
partnershipId: 'd8b674ab-3c3d-4772-b5e8-81b4c0279424',
brandId: 66
brandName: 'BrandNameId66'
,
partnerId: 107,
partnershipId: '13246d75-59ed-47c2-82c5-54f73ad25cf0',
brandId: 77
brandName: 'BrandNameId77'
]
当前结果:
partnerId: 107,
partnerName: 'TEST',
partnership:
brand: [
brandId: 1,
brandName: 'BrandNameId1'
,
...
]
请帮助我。谢谢!
【问题讨论】:
【参考方案1】:在下次查找之前,您需要先解除合作伙伴关系:
db.getCollection('partner').aggregate([
$match: partnerId: 107
,
"$lookup":
"from" : "partnership",
"localField" : "partnerId",
"foreignField" : "partnerId",
"as" : "partnership"
,
$unwind:path: "$partnership", preserveNullAndEmptyArrays: true
"$lookup" :
"from" : "brand",
"localField" : "partnership.brandId",
"foreignField" : "partnership.brandId",
"as" : "partnership.brand"
$group:
_id:"$_id",
partnerId:$min:"$partnerId",
partnerName:$min:"$partnerName",
partnership:$push:"$partnership"
])
【讨论】:
哇,感谢@sushant mehta 的回答,我只是将foreignField 值从partnership.brandId 更改为brandId,并得到了结果以上是关于链式查找聚合 mongoDB 多个集合的主要内容,如果未能解决你的问题,请参考以下文章