查找和合并嵌套数组

lookup and merge nested arrays

我有两个集合要合并。首先是 'books'

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

第二个是'authors'

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

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

您可以使用以下聚合。

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