標籤:Python串連MongoDB資料庫並 python 串連 mongodb資料庫
環境設定:
[[email protected] ~]# cat /etc/redhat-release CentOS release 6.9 (Final)[[email protected] ~]# python -VPython 2.6.6
1.首先確保,Mongodb資料庫運行
2.安裝pymongo模組
官網:https://pypi.python.org/pypi/pymongo/(按需下載)
[[email protected] src]# wget https://pypi.python.org/packages/a3/fe/826348375bfe2d11c96cdc7b7cbabbd84b8b15b62eb33638ee3241fca5f9/pymongo-3.6.1.tar.gz#md5=0d72c87fb93cea0759529befafefce54[[email protected] src]# tar -zxvf pymongo-3.6.1.tar.gz [[email protected] src]# cd pymongo-3.6.1[[email protected] pymongo-3.6.1]# python setup.py install
3.開始編寫python指令碼,串連Mongodb資料庫
[[email protected] ~]# 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.執行指令碼,進庫查詢是否更新集合資料
[[email protected] ~]# /opt/mongodb/bin/mongo
MongoDB shell version v3.4.5connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.5> use testswitched to db test> db.test.find(){ "_id" : ObjectId("5ab174b2685a5f0b11f67b4f"), "title" : "this is update test" }> #更新成功
Python串連MongoDB 成功!!!!
Python串連MongoDB資料庫並執行操作