发布时间:2019-09-10 09:20:15编辑:auto阅读(2078)
环境设置:
[root@mongodb ~]# cat /etc/redhat-release CentOS release 6.9 (Final) [root@mongodb ~]# python -V Python 2.6.6
1.首先确保,Mongodb数据库运行

2.安装pymongo模块
官网:https://pypi.python.org/pypi/pymongo/(按需下载)
[root@mongodb src]# wget https://pypi.python.org/packages/a3/fe/826348375bfe2d11c96cdc7b7cbabbd84b8b15b62eb33638ee3241fca5f9/pymongo-3.6.1.tar.gz#md5=0d72c87fb93cea0759529befafefce54 [root@mongodb src]# tar -zxvf pymongo-3.6.1.tar.gz [root@mongodb src]# cd pymongo-3.6.1 [root@mongodb pymongo-3.6.1]# python setup.py install
3.开始编写python脚本,连接Mongodb数据库
[root@mongodb ~]# cat mongodb.py
#!/usr/bin/env python
#-*- coding: UTF-8 -*-
#导入模块
from pymongo import MongoClient
#建立Mongodb数据库连接
client=MongoClient('localhost',27017)
#test为数据库
db=client.test
#test为集合,相当于表名
collection=db.test
#插入集合数据
collection.insert({"title":"test"})
#打印集合中所有数据
for item in collection.find():
print item
#更新集合里的数据
collection.update({"title":"test"},{"title":"this is update test"})
#关闭连接
client.close()
#!!!!其他操作
#查找集合中单条数据
#print collection.find_one()
#删除集合collection中的所有数据
#collection.remove()
#删除集合collection
#collection.drop()4.执行脚本,进库查询是否更新集合数据

[root@mongodb ~]# /opt/mongodb/bin/mongo
MongoDB shell version v3.4.5
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.5
> use test
switched to db test
> db.test.find()
{ "_id" : ObjectId("5ab174b2685a5f0b11f67b4f"), "title" : "this is update test" }
> #更新成功Python连接MongoDB 成功!!!!
上一篇: Python 通过telnet 配置思科
下一篇: Python获取Linux或Window
51168
50576
41198
38027
32490
29393
28256
23110
23075
21395
1452°
2172°
1794°
1718°
2024°
1789°
2467°
4153°
4018°
2867°