【问题标题】:lookup and merge nested arrays查找和合并嵌套数组
【发布时间】:2019-03-16 08:04:31
【问题描述】:

我有两个要与聚合相结合的集合。首先是“书”

{
    "_id": "56e31ce076cdf52e541d9d28",
    "title": "Good Omens",
    "author": [
        { 
             "_id": "56e31ce076cdf50ssdksi998j",
             "function": "Writer"
        },
        {
             "_id": "56e31ce076cdf52e541d9d29",
             "function": "Illustrator"
        }
    ]
}

第二个是“作者”

{
    "_id": "56e31ce076cdf50ssdksi998j",
    "name": "Terry Pratchett"
}
{
    "_id": "56e31ce076cdf52e541d9d29",
    "name": "Neil Gaiman"
}

我期望的结果是这样的:

{
    "_id": "56e31ce076cdf52e541d9d28",
    "title": "Good Omens",
    "author": [
        { 
             "_id": "56e31ce076cdf50ssdksi998j",
             "function": "Writer",
             "name": "Terry Pratchett"
        },
        {
             "_id": "56e31ce076cdf52e541d9d29",
             "function": "Illustrator",
             "name": "Neil Gaiman"
        }
    ]
}

但我无法合并两个数组。到目前为止,我一直在尝试的方法是使用带有查找和项目的聚合查询,但它没有组合数组。 如果我这样做:

Books.aggregate([
    {
        $lookup: {
            from: 'authors',
            localField: 'author._id',
            foreignField: '_id',
            as: 'authors'
        }
    }
    {
        $project: {
            title: 1,
            'authors._id': 1,
            'authors.name': 1,
            'authors.function': '$author.function'
        } 
    }
])
.exec(...)

我得到这样的东西:

{
    "_id": "56e31ce076cdf52e541d9d28",
    "title": "Good Omens",
    "author": [
        { 
             "_id": "56e31ce076cdf50ssdksi998j",
             "function": ["Writer", "Illustrator"],
             "name": "Terry Pratchett"
        },
        {
             "_id": "56e31ce076cdf52e541d9d29",
             "function": ["Writer", "Illustrator"],
             "name": "Neil Gaiman"
        }
    ]
}

但我不想得到每个作者的所有数据,只是按位置对应。 谢谢!

【问题讨论】:

    标签: mongodb mongoose aggregation-framework aggregate lookup


    【解决方案1】:

    您可以使用以下聚合。

    Books.aggregate([
      {"$unwind":"$author"},
      {"$lookup":{
        "from":"authors",
        "localField":"author._id",
        "foreignField":"_id",
        "as":"author.name"
      }},
      {"$addFields":{"author.name":{"$arrayElemAt":["$author.name",0]}}},
      {"$group":{
        "_id":"$_id",
        "title":{"$first":"$title"},
        "author":{"$push":"$author"}
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-18
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      相关资源
      最近更新 更多