首页 > 解决方案 > 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",

标签: mongodbaggregation-framework

解决方案


意识到我的数组是嵌套的,所以我需要通过执行另一个$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

推荐阅读