首页 > 解决方案 > 查找数组内的所有文档 - MongoDB 聚合

问题描述

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

收藏:

{
  {
    "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'”

标签: mongodbaggregation-frameworkaggregation

解决方案


您可以使用以下聚合

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" }]
        }
    }}
])

推荐阅读