Pau*_*eev 4 mongodb aggregation-framework
我有两个数组:
[
{
name: 'First object',
value: 1
},
{
name: 'Second object',
value: 2
},
{
name: 'Third object',
value: 3
},
];
Run Code Online (Sandbox Code Playgroud)
和
[
{
name: 'First object',
anotherValue: 1,
},
{
name: 'Second object',
anotherValue: 2,
},
{
name: 'Third object',
anotherValue: 3,
},
];
Run Code Online (Sandbox Code Playgroud)
我可以使用 MongoDB 聚合使用这两个数组来获取新数组吗?我是说:
[
{
name: 'First object',
value: 1,
anotherValue: 1,
},
{
name: 'Second object',
value: 2,
anotherValue: 2,
},
{
name: 'Third object',
value: 3,
anotherValue: 3,
},
];
Run Code Online (Sandbox Code Playgroud)
我尝试使用facet,concatArrays和group来获取该数组,但它不起作用:
{
$facet: {
$firstArray: [...],
$secondArray: [...],
}
$project: {
mergedArray: {
$concatArrays: [firstArray, secondArray],
}
},
$group: {
_id: {
name: '$mergedArray.name'
},
value: {
$first: '$mergedArray.value'
},
anotherValue: {
$first: '$mergedArray.anotherValue'
}
},
}
Run Code Online (Sandbox Code Playgroud)
但$anotherValue始终为空。
有没有一种通过聚合框架实现这一点的巧妙方法?
Val*_*jon 10
要匹配 by 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
]
}
]
}
}
}
}
}
])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3185 次 |
| 最近记录: |