Mongodb 如何使用$dateFromString转换数组中的日期?
我正在尝试将数组中的时间戳转换为带有$dateFromString的日期 我试图转换日期的示例文档:Mongodb 如何使用$dateFromString转换数组中的日期?,mongodb,aggregation-framework,pymongo,Mongodb,Aggregation Framework,Pymongo,我正在尝试将数组中的时间戳转换为带有$dateFromString的日期 我试图转换日期的示例文档: { "_id" : ObjectId("5cbc5efc8af5053fd8bdca31"), "ticker" : "ticker", "currency" : "currency", "daily" : [ { "timestamp" : "2019-04-18", "open" : "5.33
{
"_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应用于包含数百个元素的数组吗?您可以使用将$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"
}
}
}
}
}])