我有两个数组:
[
{
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
始终为空。
是否有通过聚合框架实现此目标的简便方法?
答案 0 :(得分:0)
要通过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
]
}
]
}
}
}
}
}
])
MongoPlayground | Arrays with the same position + name
value