python - mongo db 日期保存为字符串,使用 RoboMongo 或 Python 的 PyMongo 转换为 ISO 日期
问题描述
首先,我不是 mongo db 专家,所以我可能会有一些新手错误。我有一个 mongodb 数据库,它是不久前用 pymongo 创建的,来自解析 json。一段示例代码是这样的:
data = {parsed_json['location']['city']:
'local_time': parsed_json['current_observation']['local_time_rfc822'],
'full_name': parsed_json['current_observation']
['observation_location']['full'],
'latitude': float(parsed_json['current_observation']
['observation_location']
['latitude']),
'longitude': float(parsed_json['current_observation']
['observation_location']
['longitude']),
'elevation_ft': float(parsed_json['current_observation']
['observation_location']
['elevation'].split(' ')[0])
}}
collection = db[state_to_insert]
collection.insert_one(data)
print 'Inserted data successfully'
db 中的输出如下所示,但是,“local_time”字段之一以错误的格式保存(字符串而不是日期)。
{
"_id" : ObjectId("5adb54ff59aea50aec2856bf"),
"Ithaca" : {
"weather" : "Clear",
"full_name" : "Ithaca, New York",
"windchill_f" : 47.0,
"solarradiation" : 786,
"heat_index" : "NA",
"latitude" : 44.7,
"wind_mph" : 0.0,
"dewpoint" : 23,
"precip_today_in" : 0.0,
"temp_f" : 47.0,
"elevation_ft" : 174.0,
"pressure_trend" : "0",
"visibility_mi" : 10.0,
"wind_string" : "Calm",
"pressure_in" : 30.34,
"wind_dir" : "NNW",
"wind_degrees" : 336.0,
"relative_humidity_perc" : 0.38,
"uv" : 3.7,
"longitude" : -73.47,
"local_time" : "Sat, 21 Apr 2018 11:13:03 -0400",
"wind_gust_mph" : 0.0,
"feels_like" : 47
}
}
我的数据库在本地机器上运行,在一个有一个名为“NY”的集合的数据库中:
为了修复数据类型,以便我可以按日期正确查询数据库,在 robomongo 中,我运行以下代码:
db.NY.find().forEach(function(element){
element.local_time = new Date(element.local_time);
db.NY.save(element);
})
产生以下输出:
{
"_id" : ObjectId("5adb54ff59aea50aec2856bf"),
"Ithaca" : {
"weather" : "Clear",
"full_name" : "Ithaca, New York",
"windchill_f" : 47.0,
"solarradiation" : 786,
"heat_index" : "NA",
"latitude" : 44.7,
"wind_mph" : 0.0,
"dewpoint" : 23,
"precip_today_in" : 0.0,
"temp_f" : 47.0,
"elevation_ft" : 174.0,
"pressure_trend" : "0",
"visibility_mi" : 10.0,
"wind_string" : "Calm",
"pressure_in" : 30.34,
"wind_dir" : "NNW",
"wind_degrees" : 336.0,
"relative_humidity_perc" : 0.38,
"uv" : 3.7,
"longitude" : -73.47,
"local_time" : "Sat, 21 Apr 2018 11:13:03 -0400",
"wind_gust_mph" : 0.0,
"feels_like" : 47
},
"local_time" : ISODate("1970-01-01T00:00:00.000Z")
}
因此,该功能似乎在 robomongo 中工作,但是,该行为不是预期的,因为:
“local_time”:“2018 年 4 月 21 日星期六 11:13:03 -0400”
转化为:
“本地时间”:ISODate(“1970-01-01T00:00:00.000Z”)
此外,记录中的所有其他日期都是相同的。这里有什么问题?任何人都可以指出错误在哪里?
解决方案
element.local_time
你的forEach
. element
这是文档,所以应该是:
db.NY.find().forEach(function(element){
element.local_time = new Date(element.Ithaca.local_time);
db.NY.save(element);
})
推荐阅读
- javascript - 如何在javascript中求和两个时间值
- swift - 在 MacOS 中注册像 Snap Camera 这样的相机设备
- r - 如何将一个表中的一列数据插入到另一个表中?
- html - 我可以在另一个 html 中链接另一个 HTML 文件吗?
- javascript - 带有Firebase的角度类似帖子的系统的问题
- azure - 将 VHD 从 azure 磁盘复制到 azure 存储帐户
- swift - 无法弄清楚快速 POST 请求错误
- pyspark - 如何将 pyspark 数据帧转换为 JSON?
- mysql - MYSQL 远程访问适用于一个用户,而不是另一个
- html - CSS 按钮未正确突出显示