python調用MongoDB

來源:互聯網
上載者:User

標籤:

-------------------python調用MongoDB-------------------1、官方文檔:http://api.mongodb.org/python/current/tutorial.html 2、linux下安裝指令:sudo pip install pymongo 3、測試python驅動:
 1 #coding=utf-8 2  3 ‘‘‘ 4 測試python驅動 5 ‘‘‘ 6  7 #引用對應的包 8 import pymongo 9 10 #建立一個mongo用戶端對象11 client = pymongo.MongoClient("127.0.0.1",27017)12 #獲得mongoDB中的資料庫物件13 db = client.test_database14 #在資料庫中建立一個集合15 collection = db.test_collectionTwo16 17 #建立一條要加入資料庫中的資料資訊,json格式18 post_data = {"username":"xiaohao","pwd":"123456",}19 20 #進行資料的添加操作,inserted_id返回添加後的id編號資訊21 post_data_id = collection.insert_one(post_data).inserted_id22 23 #展示一下插入的資料資訊24 print collection.find_one()25 26 #列印當前資料庫中所有集合的民稱27 print db.collection_names()28 29 #列印當前集合中資料的資訊30 for item in collection.find():31     print item32 33 #列印當前集合中資料的個數34 print collection.count()35 36 #進行find查詢,並列印查詢到的資料的條數37 print collection.find({"username":"xiaohao"}).count()

4、Aggregation Examples:mongoDB彙總練習

 1 #coding=utf-8 2  3 ‘‘‘ 4 進行彙總aggregation 練習 5 ‘‘‘ 6  7 #引包 8 import pymongo 9 10 client = pymongo.MongoClient("127.0.0.1",27017)11 12 db = client.aggregation_database13 14 collection = db.aggregation_collection15 16 collection.insert_many([17     {"username":"xiaohao01","pwd":"111"},18     {"username":"xiaohao02","pwd":"222"},19     {"username":"xiaohao03","pwd":"333"}20 ])21 22 23 # for item in collection.find():24 #     print item25 26 #python中不含有son文法,需要使用son27 28 from bson.son import SON29 30 pipeline = [31     {"$unwind":"$pwd"},32     {"$group":{"_id":"pwd","count":{"$sum":1}}},33     {"$sort":SON([("count",-1),("_id",-1)])}34 ]35 36 result = list(collection.aggregate(pipeline))37 38 print result

 

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.