查找和合并嵌套数组
Posted
技术标签:
【中文标题】查找和合并嵌套数组【英文标题】: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"
]
但我不想得到每个作者的所有数据,只是按位置对应。 谢谢!
【问题讨论】:
【参考方案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"
])
【讨论】:
以上是关于查找和合并嵌套数组的主要内容,如果未能解决你的问题,请参考以下文章