查找并合并嵌套数组

时间:2018-10-11 09:29:00

标签: mongodb mongoose aggregation-framework aggregate lookup

我有两个集合要结合使用。首先是“书”

{
    "_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"
        }
    ]
}

但是我不想获取每个作者的所有数据,而只是按位置获取相应的数据。 谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用以下汇总。

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