【问题标题】:lookup on all documents inside an array - MongoDB aggregation查找数组内的所有文档 - MongoDB 聚合
【发布时间】:2020-05-17 17:48:51
【问题描述】:

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

收藏:

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

【问题讨论】:

  • 显示您的 mertas 集合文档和预期输出。

标签: mongodb aggregation-framework aggregation


【解决方案1】:

你可以使用下面的聚合

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

【讨论】:

  • 以上查询有一些错误,请删除 $ 登录查找字段。因为字段值使用没有 $ 登录查找关键字。
  • 我猜$_id:$_id应该是_id:$_id在组内
  • @saketh hmm 还有一个。实际上在没有测试的情况下在编辑器上编写了手头的脚本。谢谢!!!
  • 谢谢,它几乎可以工作了。但是姓名和年龄字段丢失,最终结果只有一个回复字段。 (在我的真实收藏中,除了replies,我还有很多字段,我没有它们的列表)。 @Ashh
猜你喜欢
  • 2023-03-30
  • 2020-10-10
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 2021-02-24
相关资源
最近更新 更多