【发布时间】:2020-02-12 22:28:51
【问题描述】:
使用 MongoDB 4.2 和 MongoDB Atlas 测试聚合管道。
我有这个 products 集合,其中包含具有此架构的文档:
{
"name": "TestProduct",
"relatedList": [
{id:ObjectId("someId")},
{id:ObjectId("anotherId")}
]
}
然后是这个 cities 集合,包含具有此架构的文档:
{
"name": "TestCity",
"instructionList": [
{ related_id: ObjectId("anotherId"), foo: bar},
{ related_id: ObjectId("someId"), foo: bar}
{ related_id: ObjectId("notUsefulId"), foo: bar}
...
]
}
我的目标是加入两个集合以输出类似这样的内容(操作是从城市文档中的指令列表中挑选每个相关对象,将其放入产品文档的相关列表中):
{
"name": "TestProduct",
"relatedList": [
{ related_id: ObjectId("someId"), foo: bar},
{ related_id: ObjectId("anotherId"), foo: bar},
]
}
我尝试使用 $lookup 运算符进行聚合,例如 this:
$lookup:{
from: 'cities',
let: {rId:'$relatedList._id'},
pipeline: [
{
$match: {
$expr: {
$eq: ["$instructionList.related_id", "$$rId"]
}
}
},
]
}
但它不起作用,我对这种复杂的管道语法有点迷茫。
编辑
通过在两个数组上使用展开:
{
{$unwind: "$relatedList"},
{$lookup:{
from: "cities",
let: { "rId": "$relatedList.id" },
pipeline: [
{$unwind:"$instructionList"},
{$match:{$expr:{$eq:["$instructionList.related_id","$$rId"]}}},
],
as:"instructionList",
}},
{$group: {
_id: "$_id",
instructionList: {$addToSet:"$instructionList"}
}}
}
我能够实现我想要的,但是, 我根本没有得到干净的结果:
{
"name": "TestProduct",
instructionList: [
[
{
"name": "TestCity",
"instructionList": {
"related_id":ObjectId("someId")
}
}
],
[
{
"name": "TestCity",
"instructionList": {
"related_id":ObjectId("anotherId")
}
}
]
]
}
如何将所有内容分组,使其与我最初的问题所述一样干净? 同样,我完全迷失了聚合框架。
【问题讨论】: