MongoDB之pymongo

來源:互聯網
上載者:User

標籤:desc   collect   cli   tps   localhost   href   python2   display   end   

PyMongo是什麼 PyMongo是驅動程式,使python程式能夠使用Mongodb資料庫,使用python編寫而成.安裝 環境:Ubuntu 14.04+python2.7+MongoDB 2.4    先去官網下載軟體包,地址點擊開啟連結.解壓縮後進入,使用 python setup.py install  進行安裝    或者用pip安裝 pip -m install pymongo基本使用 建立串連
  1. import pymongo  
  2. client = pymongo.MongoClient(‘localhost‘, 27017)  

 或者可以這樣 

  1. import pymongo  
  2. client = MongoClient(‘mongodb://localhost:27017/‘)  
    串連資料庫
  1. db = client.mydb  
 或者
  1. db = client[‘mydb‘]  
串連聚集 聚集相當於關係型資料庫中的表
  1. collection = db.my_collection  
 或者 
  1. collection = db[‘my_collection‘]  
查看資料庫下所有聚集名稱
  1. db.collection_names()  
  插入記錄
  1. collection.insert({"key1":"value1","key2","value2"})  
 刪除記錄

 全部刪除

  1. collection.remove()  
    按條件刪除
  1. collection.remove({"key1":"value1"})  
 更新記錄
  1. collection.update({"key1": "value1"}, {"$set": {"key2": "value2", "key3": "value3"}})  
 查詢記錄 查詢一條記錄:find_one()不帶任何參數返回第一條記錄.帶參數則按條件尋找返回
  1. collection.find_one()  
  2. collection.find_one({"key1":"value1"})  
 查詢多條記錄:find()不帶參數返回所有記錄,帶參數按條件尋找返回
  1. collection.find()  
  1. collection.find({"key1":"value1"})  
查看聚集的多條記錄  
  1. for item in collection.find():      
  2.     print item  
 查看聚集記錄的總數
  1. print collection.find().count()  
 查詢結果排序 單列上排序 
  1. collection.find().sort("key1") # 預設為升序  
  2. collection.find().sort("key1", pymongo.ASCENDING) # 升序  
  3. collection.find().sort("key1", pymongo.DESCENDING) # 降序  
 多列上排序
  1. collection.find().sort([("key1", pymongo.ASCENDING), ("key2", pymongo.DESCENDING)])  

MongoDB之pymongo

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.