Python使用MongoDB一(Python mongodb)

网友投稿 345 2022-08-23


Python使用MongoDB一(Python mongodb)

在PyCharm中安装Mongo Plugin

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

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

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

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

将数据存入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='i in range(3): data1.remove(data1[0])for item in data1: url=' strhtml=requests.get(url) time.sleep(1) dic=strhtml.json() # 写入一条数据 sheet_weather.insert_one(dic)

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

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

查询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'])


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:python实现骚操作,表白神技:整个朋友圈都是爱你的样子(用python表白女神)
下一篇:JAVA观察者模式的的讲解及代码实现
相关文章

 发表评论

暂时没有评论,来抢沙发吧~