问题描述
我正在尝试使用$ dateFromString将数组中的时间戳转换为日期
I'm trying to convert timestamps in an array to dates with $dateFromString
我要转换日期的示例文档:
Sample document which I'm trying to convert dates from:
{
"_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中的聚合查询:
Aggregation query in 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" ....]
pymongo.errors.OperationFailure: $dateFromString requires that 'dateString' be a string, found: array with value ["2019-04-18", "2019-04-17", "2019-04-16", "2019-04-15"....]
甚至可以将$ dateFromString应用于具有数百个元素的数组吗?
Is it even possible to apply $dateFromString to an array with hundreds of elements?
推荐答案
您可以使用 $ map聚合运算符将 $ dateFromString
应用于数组中的每个元素:
You can use the $map aggregation operator to apply $dateFromString
to each element in the array:
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"
}
}
}
}
}])
这篇关于如何使用$ dateFromString转换数组中的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!