8.3 操作MongoDB資料庫

來源:互聯網
上載者:User

標籤:其他   可擴充性   pymongo   分布   文檔資料庫   mon   json   rem   官方   

  一項權威調查顯示,在大資料時代軟體開發人員必備的十項技能中MongoDB資料庫名列第二,僅次於HTML5。MongoDB是一個基於分布式檔案儲存體的文檔資料庫,可以說是非關係型(Not Only SQL,NoSQL)資料庫中比較像關係型資料庫的一個,具有免費、操作簡單、面向文檔儲存、自動分區可擴充性強、查詢功能強大等特點,對大資料處理支援較好,旨在為Web應用提供可擴充的高效能資料儲存解決方案。MongoDB將資料存放區為一個文檔,資料結構由索引值(key -> value)對組成。MongoDB文檔類似於JSON對象。欄位值可以包含其他文檔、數組和文檔數組。

  MongoDB資料庫可以到官網下載,安裝教程可以自行百度。

  Python擴充庫pymongo完美支援MongoDB資料的操作,可以使用pip命令進行安裝。下面的代碼示範了pymongo操作MongoDB資料庫的一部分用法,算是拋磚引玉吧,更多的用法可以學習使用Python的利器dir()和help()來獲得,或者查閱MongoDB官方文檔。

 1 import pymongo                #匯入模組 2  3 client = pymongo.MongoClint(‘localhost‘,27017)    #串連資料庫,27017是預設連接埠 4 db = client.students                              #擷取資料庫 5 db.collection_names()                             #查看資料集合名稱列表  6 students = db.students                            #擷取資料集合 7 students.find() 8  9 for item in students.find():                      #遍曆資料10     print(item)11     12 wangwu={‘name‘:‘Wangwu‘,‘age‘:20,‘sex‘:‘male‘}13 students.insert(wangwu)                           #插入一條記錄14 for item in students.find({‘name‘:‘Wangwu‘}):    #指定查詢條件15     print(item)16 17 students.find_one()                               #擷取一條記錄18 students.find_one({‘name‘:‘Wangwu‘})19 students.find().count()                           #擷取記錄總數20 students.remove({‘name‘:‘Wangwu‘})                #刪除一條記錄21 22 students.create_index((‘name‘,pymongo.ASCENDING))  #建立索引23 24 students.update({‘name‘:‘Zhangsan‘},{‘$set‘:{‘age‘:25}})   #更新資料庫25 26 students.remove()                                  #清空資料庫27 28 Zhangsan = ‘‘29 Lisi = ‘‘30 Wangwu = ‘‘31 students.insert_many([Zhangsan,Lisi,Wangwu])      #插入多條資料32 33 for item in students.find().sort(‘name‘,pymongo.ASCENDING):   #對查詢結果排序34     print(item)35     

 

8.3 操作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.