时间:2021-07-01 10:21:17 帮助过:2人阅读
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
python调用MongoDB
标签: