我正试图将数组中的时间戳转换为带有$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”是一个字符串,found:array的值为[“2019-04-18”、“2019-04-17”、“2019-04-16”、“2019-04-15”。…]
甚至可以将$datefromstring应用于包含数百个元素的数组吗?

最佳答案

您可以使用$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"
        }
      }
    }
  }
}])

09-11 03:40