【问题标题】:How to convert dates in an array with $dateFromString?如何使用 $dateFromString 转换数组中的日期?
【发布时间】:2019-05-12 03:08:29
【问题描述】:

我正在尝试使用 $dateFromString 将数组中的时间戳转换为日期

我试图从中转换日期的示例文档:

{
    "_id" : ObjectId("5cbc5efc8af5053fd8bdca31"),
    "ticker" : "ticker",
    "currency" : "currency",
    "daily" : [ 
        {
            "timestamp" : "2019-04-18",
            "open" : "5.3300",
            "high" : "5.3300",
            "low" : "5.2000",
            "close" : "5.2700",
            "volume" : "6001"
        }, 
        {
            "timestamp" : "2019-04-17",
            "open" : "5.1500",
            "high" : "5.2900",
            "low" : "5.1500",
            "close" : "5.2700",
            "volume" : "37659"
        }, 
        {
            "timestamp" : "2019-04-16",
            "open" : "4.7100",
            "high" : "5.3000",
            "low" : "4.7100",
            "close" : "5.1500",
            "volume" : "112100"
        }
    ]
}

pymongo 中的聚合查询:

db.test.aggregate([{
        '$project': {
            'daily.timestamp': {
                '$dateFromString': {
                    'dateString': '$daily.timestamp',
                    'format':  '%Y-%m-%d'
                }
            }
        }
    }])

这会引发以下错误:

pymongo.errors.OperationFailure: $dateFromString 要求 'dateString' 是一个字符串,找到:数组,值为 ["2019-04-18", "2019-04-17", "2019-04-16", “2019-04-15”....]

是否可以将 $dateFromString 应用于包含数百个元素的数组?

【问题讨论】:

    标签: mongodb aggregation-framework pymongo


    【解决方案1】:

    您可以使用$map aggregation operator$dateFromString 应用于数组中的每个元素:

    db.test.aggregate([{
      "$project": {
        "ticker": 1,
        "currency": 1,
        "daily": {
          "$map": {
            "input": "$daily",
            "in": {
              "timestamp": { 
                "$dateFromString": {
                  "dateString": '$$this.timestamp',
                  "format":  '%Y-%m-%d'
                }
              },
              "open": "$$this.open",
              "high": "$$this.high",
              "low": "$$this.low",
              "close": "$$this.close",
              "volume": "$$this.volume"
            }
          }
        }
      }
    }])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-14
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多