查找数组中的所有文档 - MongoDB 聚合

lookup on all documents inside an array - MongoDB aggregation

我需要对数组中的所有文档执行查找阶段。

合集:

{
  {
    "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": "$$ROOT" },
        "replies": { "$push": "$replies" }
    }},
    { "$replaceRoot": {
        "newRoot": {
            "$mergeObjects": ["$data", { "replies": "$replies" }]
        }
    }}
])