【发布时间】:2020-09-03 02:00:15
【问题描述】:
我有两个数组:
[
{
name: 'First object',
value: 1
},
{
name: 'Second object',
value: 2
},
{
name: 'Third object',
value: 3
},
];
和
[
{
name: 'First object',
anotherValue: 1,
},
{
name: 'Second object',
anotherValue: 2,
},
{
name: 'Third object',
anotherValue: 3,
},
];
我可以使用这两个使用 MongoDB 聚合来获得新数组吗?我的意思是:
[
{
name: 'First object',
value: 1,
anotherValue: 1,
},
{
name: 'Second object',
value: 2,
anotherValue: 2,
},
{
name: 'Third object',
value: 3,
anotherValue: 3,
},
];
我尝试使用facet、concatArrays 和group 来获取该数组,但它不起作用:
{
$facet: {
$firstArray: [...],
$secondArray: [...],
}
$project: {
mergedArray: {
$concatArrays: [firstArray, secondArray],
}
},
$group: {
_id: {
name: '$mergedArray.name'
},
value: {
$first: '$mergedArray.value'
},
anotherValue: {
$first: '$mergedArray.anotherValue'
}
},
}
但$anotherValue 始终为空。
聚合框架有没有一种巧妙的方法来实现这一点?
【问题讨论】:
标签: mongodb aggregation-framework