我收集了books
份文件:
{
title: "My book",
authors: [{id: 1, date: "2023-12-20"},{id: 2, date: "2023-12-21"}],
authorsDetails: [{id: 2, name:"Author 2", age: 25}, {id: 1, name: "Author 1", age: 38}],
}
我需要进行聚合,结果必须返回以下结果:
{
title: "My book",
authors: [{id: 1, date: "2023-12-20", name: "Author 1"},{id: 2, date: "2023-12-21", name: "Author 2"}],
}
基本上我需要添加一些信息从authorsDetails
到authors
.在这种情况下,只有名字.
注意:这两个数组不需要以相同的方式排序.
我试了$addFields
管+$map
,但还不够.我试过这个:
const pipeline = [
//...
{
$addFields: {
indices: { $range: [0, { $size: '$authors' }] },
},
},
{
$addFields: {
admins: {
$map: {
input: '$indices',
as: 'index',
in: {
detail: { $arrayElemAt: ['$authorsDetails', '$$index'] },
author: { $arrayElemAt: ['$authors', '$$index'] },
},
},
},
},
},
//...
]
只有当数组以相同的方式排序时才有效.我还需要做另一个 map 来解决这个问题,因为我希望.
你知道怎么做吗?