MongoDB-python的API手記


-------------------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_database
14 #在數據庫中創建一個集合
15 collection = db.test_collectionTwo
16 
17 #創建一條要加入數據庫中的數據信息,json格式
18 post_data = {"username":"xiaohao","pwd":"123456",}
19 
20 #進行數據的添加操作,inserted_id返回添加后的id編號信息
21 post_data_id = collection.insert_one(post_data).inserted_id
22 
23 #展示一下插入的數據信息
24 print collection.find_one()
25 
26 #打印當前數據庫中所有集合的民稱
27 print db.collection_names()
28 
29 #打印當前集合中數據的信息
30 for item in collection.find():
31     print item
32 
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_database
13 
14 collection = db.aggregation_collection
15 
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 item
25 
26 #python中不含有son語法,需要使用son
27 
28 from bson.son import SON
29 
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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM