mongodb - How to convert datestrings in an array generated by $push in aggregation?
问题描述
This is similar to this question,
I'm trying to convert timestamps in an array generated from $push
in aggregation pipeline to convert dates with $dateFromString
Aggreagtion Pipeline:
{
'$match': {
'metadata.client': 'client_id'
}
}, {
'$limit': 10
}, {
'$lookup': {
'from': 'steps',
'localField': 'connection_id',
'foreignField': 'connection_id',
'as': 'joined_steps_array'
}
}, {
'$group': {
'_id': '$_id',
'tsArr': {
'$push': '$joined_steps_array.timestamp'
},
'stepsArr': {
'$push': '$joined_steps_array.metadata.step_info'
},
'metadata': {
'$push': {
'$arrayElemAt': [
'$joined_steps_array', 0
]
}
}
}
}, {
'$project': {
'_id': 1,
'convertedTsArr': {
'$map': {
'input': '$tsArr',
'in': {
'$dateFromString': {
'dateString': '$$this'
}
}
}
}
}
}
My Array looks something like:
tsArr:Array
0:Array
0:"2020-09-16T09:18:50.806Z"
1:"2020-09-16T09:18:50.983Z"
2:"2020-09-16T09:18:51.164Z"
3:"2020-09-16T09:18:50.855Z"
4:"2020-09-16T09:18:51.044Z"
I am getting this error in the project stage where I am trying to $map
:
$dateFromString requires that 'dateString' be a string,
found: array with value ["2020-09-18T00:09:05.569Z", "2020-09-18T00:16:59.297Z",
解决方案
意识到我的数组是嵌套的,所以我需要通过执行另一个$map
. 成功了。
{
_id: 1,
convertedTsArr: {
$map: {
input: '$tsArr',
in: {
$map: {
input: '$$this',
in: {
$dateFromString: {
dateString: '$$this'
}
}
}
}
}
}
}
转换数组:
convertedTsArr:Array
0:Array
0:2020-09-18T00:10:52.542+00:00
1:2020-09-18T00:31:21.980+00:00
2:2020-09-18T00:44:51.123+00:00
3:2020-09-18T00:57:14.435+00:00
4:2020-09-18T01:18:33.845+00:00
推荐阅读
- python - Nagios 检查给出错误而不是我期望的输出
- python - Anaconda基础环境VScode中无法导入库错误
- sqlite - 附加行之前的 SQLite 索引
- spring-boot - 如何定义递归 URL 消费逻辑
- getgauge - 如何在 taiko 中启动 chrome 浏览器而不是 chromium,因为我是 taiko 的新手
- python - 将文件保存到 Azure Blob 存储
- android - 在 Android Studio (java) 中使用 ConstraintLayout 实现弹出窗口
- c - winsock2:RAW SOCKET recvfrom() 返回错误 10022(无效参数)
- swift - 使用 NSBezierPath、CAShapeLayer 和 CAGradientLayer 绘制一条带渐变的线
- python - 解决四和问题的时间复杂度?