实验楼python3获取MongoDB数据总结
对这次挑战做总结
新手,对MongoDB不是特别熟,查了好多资料看了一些MongoDB的API,在此做个记录。
启动MongoDB服务,导入数据
sudo service mongod start
mongoimport --db shiyanlou --collection contests --file /home/shiyanlou/Code/contests.json --jsonArray
MongoDB数据aggregate操作
挑战的要求是给一系列含有user_id
和分数score
以及学习时间time
的用户数据,输入任意用户的user_id
,返回rank
和分数和以及时间和(一个用户可能含有多条记录), 这边最后的思路是对数据进行aggregate操作,pymongo
的操作和mongo shell的操作不太一样,在Python里需要使用pipeline,把aggregate操作的语句放入pipeline里,这个pipeline是一个包含dict的list,
pipeline = [
{"$group": {"_id": "$user_id", "totalscore": {"$sum": "$score"},
"totaltime": {"$sum": "$submit_time"}}},
{"$sort": {"totalscore": -1, "totaltime": 1}},
]
db.contests.aggregate(pipeline)
先按user_id
进行分组,在后对score
和time
进行sum求和,这里发现并没有按照totalscore降序排列,totaltime升序排列,查找原因发现:在mongo shell里,totalscore在前面就表示先排序,totaltime在后面后排序,但是在Python里,dict并没有维护这种顺序,所以上述在mongo shell里的这种顺序关系在Python中不能保证,需要使用SON 或 collections.OrderedDictpymongo聚合操作,具体如下:
from bson.son import SON
pipeline = [
{"$group": {"_id": "$user_id", "totalscore": {"$sum": "$score"},
"totaltime": {"$sum": "$submit_time"}}},
{"$sort": SON([("totalscore",-1),("totaltime",1)])},
]
就可以了,但是这种操作结果把rank体现在行的记录上,第一个记录就是就是第一名,所以想着把记录存到另一个collections里,然后读出数据。
pymongo 一些操作
from pymongo import MongoClient
connection = MongoClient('localhost', 27017) #Connect to mongodb
connection.database_names() 等价 show dbs
db = connection['testdb1'] 等价 use testdb1
db.collection_names() 等价 show collections
print("posts" in db.collection_names()) #Check if collection "posts"
collection = db['posts']
print(collection.count() == 0) #检查文档集合的文档数
collection.drop() #删除文档集合