mongodb - 如何使用聚合展平数组数组
问题描述
我正在尝试使用 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"
]
}
}
}
}
}
推荐阅读
- keras - Keras:层可训练集错误不起作用
- javascript - Reactjs - 如何在视口中心显示网格
- reactjs - 通过 POST Axios 和 React-Final-Form 向数据库提交 CSV 文件的问题
- oracle - 创建过程以通过 max(date) 自动从另一个表插入
- reactjs - 如何在 useEffect Hook 中重新渲染组件
- r - 从 caret::train 获取预测的置信区间
- list - haskell 中的值构造函数
- unit-testing - 运行 Jest 测试永远循环
- flutter - 如何在 Flutter 中定位这张卡片和文字?
- c# - DirectoryEntry 和 ActiveDirectorySecurity 的授权问题