我正在尝试使用$ 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应用于具有数百个元素的数组吗?
答案 0 :(得分:0)
您可以使用$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"
}
}
}
}
}])