[英]How to merge two arrays of objects by the same field using MongoDB aggregation?
我有两个 arrays:
[
{
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
始终是 null。
聚合框架有没有一种巧妙的方法来实现这一点?
要按name
匹配,请运行以下查询:
db.collection.aggregate([
{
$project: {
anotherValue: {
$map: {
input: "$firstArray",
as: "one",
in: {
$mergeObjects: [
"$$one",
{
$arrayElemAt: [
{
$filter: {
input: "$secondArray",
as: "two",
cond: { $eq: ["$$two.name", "$$one.name"]}
}
},
0
]
}
]
}
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.