
3.3 存储数据到MongoDB
MongoDB是一个基于分布式文件存储的数据库,由C++语言编写,旨在为Web应用提供可扩展的高性能数据存储解决方案。
MongoDB是一款介于关系数据库和非关系数据库之间的产品,它在非关系数据库中功能最丰富,最像关系数据库。
3.3.1 下载并安装MongoDB
1.下载MongoDB
到MongoDB的官网下载MongoDB即可。
2.配置本地MongoDB
MongoDB每次启动时都需要在CMD中进行配置,找到安装目录下的bin文件夹路径,如图3-11所示。

图3-11
由CMD进入以下路径:

配置数据库路径,配置前要先在C盘中新建文件夹,代码如下。

代码运行结果如下所示。

再打开一个CMD,进入MongoDB确认数据库已经启动,进入bin路径,如下所示。

输入“mongo”连接数据库,显示“>”就代表MongoDB已经正常启动,如下所示。

3.3.2 在PyCharm中安装Mongo Plugin
在PyCharm中,依次执行“File”g“Settings”g“Plugins”→“Browse Repositories”命令,输入“mongo”,然后选择“Mongo Plugin”,如图3-12和图3-13所示。
安装好后重新启动PyCharm,就可以在右侧看到Mongo Explorer。
如果没有这个窗口,则可以将鼠标光标停留在左下角的图标上,然后在自动弹出的菜单中选择“Mongo Explorer”命令,如图3-14所示。

图3-12

图3-13

图3-14
接下来在Mongo Explorer窗口中单击设置按钮,创建连接(通过PyCharm File菜单中的Settings也可以设置),如图3-15所示。

图3-15
在Mongo Servers设置窗口中单击左侧的加号按钮(addServer),如图3-16所示。

图3-16
输入连接名,单击“Test Connection”(测试连接)按钮,当提示信息为“Connection test successful”时表示连接正常,然后单击“OK”按钮保存设置即可,如图3-17所示。

图3-17
3.3.3 将数据存入MongoDB中
下面尝试将获取的数据存入MongoDB中,首先输入以下代码。

运行后双击连接,可以看到名为weather的数据库,如图3-18所示。

图3-18
展开weather数据库,双击sheet_weather_3这张表(见图3-19(b)),会弹出预览窗口(见图3-19(a)),可以从该窗口中观察获取到的天气预报数据,数据以JSON格式存储在数据库中。

图3-19
可以直接在预览窗口中展开JSON的树形结构,如图3-20所示。

图3-20
需要提前安装PyMongo库,这是一个提供Python和MongoDB连接的库,使用方法如下。
1.建立连接
输入以下代码,其中localhost是主机名,27017是端口号(在默认情况下是这个参数)。

2.新建名为weather的数据库
输入以下代码:

3.新建名为sheet_weather_3的表
输入以下代码:

4.写入数据
输入以下代码:
