如何使用聚合展平数组数组
How flatten an array of arrays using aggregate
我正在尝试使用 MongoDB(3.6) 的聚合框架来展平以下数据:
array = [
[1899.99, 241.92, 869.99, 696],
[2301.45, 100],
[1468.12, 85.9],
[14.1],
[268.59, 27.6, 428.51, 173.85],
[627.29, 241.92, 413.47, 229.74],
[1687.58, 100],
[241.11]
]
而我需要的是:
result = [1899.99, 241.92, 869.99, 696, 2301.45, 100, 1468.12, 85.9, 14.1, 268.59, 27.6, 428.51, 173.85, 627.29, 241.92, 413.47, 229.74, 1687.58, 100, 241.11]
我正在使用这个查询:
db.collection.aggregate([
{
$match: { code: '11122233344' }
},
{
$project: {
vencimentos: '$response.operations.expirations.value'
}
},
{
$unwind: '$vencimentos'
},
{
$group: {
_id: 'vencimentos',
vencimentos: { $addToSet: '$vencimentos' }
}
},
])
这是查询的结果:
{
"_id" : "vencimentos",
"vencimentos" : [
[1899.99, 241.92, 869.99, 696.11],
[2301.45, 100],
[1468.12, 85.9],
[14.1],
[268.59, 27.6, 428.51, 173.85],
[627.29, 241.92, 413.47, 229.74],
[1687.58, 100],
[241.11]
]
}
谁能帮帮我?
谢谢
考虑到您当前聚合的结果,您必须添加以下步骤以获得您需要的结果:
{
$addFields: {
vencimentos: {
"$reduce": {
"input": "$vencimentos",
"initialValue": [],
"in": {
"$concatArrays": [
"$$this",
"$$value"
]
}
}
}
}
}
我正在尝试使用 MongoDB(3.6) 的聚合框架来展平以下数据:
array = [
[1899.99, 241.92, 869.99, 696],
[2301.45, 100],
[1468.12, 85.9],
[14.1],
[268.59, 27.6, 428.51, 173.85],
[627.29, 241.92, 413.47, 229.74],
[1687.58, 100],
[241.11]
]
而我需要的是:
result = [1899.99, 241.92, 869.99, 696, 2301.45, 100, 1468.12, 85.9, 14.1, 268.59, 27.6, 428.51, 173.85, 627.29, 241.92, 413.47, 229.74, 1687.58, 100, 241.11]
我正在使用这个查询:
db.collection.aggregate([
{
$match: { code: '11122233344' }
},
{
$project: {
vencimentos: '$response.operations.expirations.value'
}
},
{
$unwind: '$vencimentos'
},
{
$group: {
_id: 'vencimentos',
vencimentos: { $addToSet: '$vencimentos' }
}
},
])
这是查询的结果:
{
"_id" : "vencimentos",
"vencimentos" : [
[1899.99, 241.92, 869.99, 696.11],
[2301.45, 100],
[1468.12, 85.9],
[14.1],
[268.59, 27.6, 428.51, 173.85],
[627.29, 241.92, 413.47, 229.74],
[1687.58, 100],
[241.11]
]
}
谁能帮帮我? 谢谢
考虑到您当前聚合的结果,您必须添加以下步骤以获得您需要的结果:
{
$addFields: {
vencimentos: {
"$reduce": {
"input": "$vencimentos",
"initialValue": [],
"in": {
"$concatArrays": [
"$$this",
"$$value"
]
}
}
}
}
}