Python使用MongoDB一

Python85

在PyCharm中安装Mongo Plugin

在PyCharm中的菜单,依次选择File命令->选择settings命令->选择plugins命令->选择browse repositories命令->输入mongo,然后选择Mongo Plugin。重启PyCharm,可以在右侧看到Mongo Explorer。如果没有这个窗口,可以将鼠标光标停留在左下角的图标上,然后在自动弹出的菜单中选择Mongo Explorer命令。

Python使用MongoDB一

Python使用MongoDB一

在Mongo Explorer窗口中单击设置按钮,创建连接(在PyCharm File菜单的Setting中也可以设置)

Python使用MongoDB一

在Mongo Servers设置窗口中单击左侧加号按钮(addServer)

Python使用MongoDB一

输入连接名,然后单击"Test Connection"按钮,提示信息为"Connection test successful"时表示连接正常,然后单击右下角的OK按钮,保存设置即可。

Python使用MongoDB一

将数据存入MongoDB

import requestsimport time# 加载pymongo库import pymongo# 建立连接client = pymongo.MongoClient('localhost',27017)# 新建名为'weather'的数据库book_weather = client['weather']# 新建名为'sheet_weather_3'表sheet_weather=book_weather['sheet_weather_3']url='https://cdn.hewrather.com/china-city-list.txt'strhtml=requests.get(url)data=strhtml.textdata1=data.split("\n")for i in range(3):    data1.remove(data1[0])for item in data1:    url='https://free-api.heweather.com/v5/forecast?city='+item[0:11]+'&key=7d0daf285f64736a42261161cd3060b'    strhtml=requests.get(url)    time.sleep(1)    dic=strhtml.json()    # 写入一条数据    sheet_weather.insert_one(dic)

运行后双击连接,可以看到名为weather的数据库

Python使用MongoDB一

展开weather数据库,双击sheet_weather_3表,可以观察到天气数据,数据以JSON格式存在数据库中。

Python使用MongoDB一

查询MongoDB数据

import pymongoclient=pymongo.MongoClient('localhost',27017)book_weather = client['weather']sheet_weather=book_weather['sheet_weather_3']#查找键HeWeather5.basic.city值为北京的数据for item in sheet_weather.find(('HeWeather5.basic.city':'北京')):    print(item)#查询天气最低气温大于5摄氏度的城市名for item in sheet_weather.find()    #因为数据需要3天的天气预报,因此循环3次    for i in range(3):        tmp = item['HeWeather5'][0]['daily_forecast'][i]['tmp']['min']        #使用update方法,将表中最低气温数据修改为数值型        sheet_weather.update_one({'_id':item['_id']},{'$set':{'HeWeather5.0.daily_forecast.{}.tmp.min'.format(i):int(tmp)}})    #提取出最低气温低于5摄氏度的城市    for item in sheet_weather.find(('HeWeather5.daily_forecast.tmp.min':{'$gt':5})):        print(item['HeWeather5'][0]['basic']['city'])

Python使用MongoDB一

Python使用MongoDB一

Python使用MongoDB一

Original: https://blog.51cto.com/feishujun/5519856
Author: mb62de8abf75c00
Title: Python使用MongoDB一