Python串連MongoDB資料庫並執行操作

來源:互聯網
上載者:User

標籤: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資料庫並執行操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.