我需要在数组内的所有文档上执行查找阶段。
[收藏:
{
{
"name": "test",
"age": 2,
"replies": [
{
"title": "testtt",
"merta_id": 1
},
{
"title": "testiona",
"merta_id": 5
},
{
"title": "the thirth test",
"merta_id": 4
}
]
}
}
mertas
集合:
{
{
_id: 1,
a: "aaaa",
b: "bbbb"
},
{
_id: 5,
a: "AaAA",
b: "BbbB"
},
{
_id: 4,
a: "Aou",
b: "Boo"
}
}
预期输出:
{
{
"name": "test",
"age": 2,
"replies": [
{
"title": "testtt",
"merta_id": 1,
"merta": {
_id: 1,
a: "aaaa",
b: "bbbb"
}
},
{
"title": "testiona",
"merta_id": 5,
"merta": {
_id: 5,
a: "aaaa",
b: "bbbb"
}
},
{
"title": "the thirth test",
"merta_id": 4
"merta":{
_id: 4,
a: "Aou",
b: "Boo"
}
}
]
}
}
我需要一个聚集阶段来对“答复”上的所有文档执行查找,并添加一个新的merta
字段,该字段应从mertas
集合中进行查找。我尝试使用$map
阶段,但收到错误“无法识别的管道阶段名称:'$ lookup'”
您可以在下面的聚合中使用
db.collection.aggregate([
{ "$unwind": "$replies" },
{ "$lookup": {
"from": "mertas",
"localField": "$replies.merta_id",
"foreignField": "$_id",
"as": "replies.merta"
}},
{ "$unwind": "$replies.merta" },
{ "$group": {
"$_id": "$_id",
"data": { "$first": "$data" },
"replies": { "$push": "$replies" }
}},
{ "$replaceRoot": {
"newRoot": {
"$mergeObjects": ["$data", { "replies": "$replies" }]
}
}}
])