【发布时间】: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