使用mongo作分页查询python
我使用的是pymongo,pymongo的函数库很是接近mongo的原生命令行。mysql
在使用普通的find查找的时候,能够使用pymongo的limit与skip函数sql
形如:函数
cursor = db.compo_message.find( { "上传人":updateuser, "$and":[ {"上传时间":{"$regex":updatetime}}, {"公司":{"$regex":company}}, {"元件类型":{"$regex":component_type}}, {"元件号":{"$regex":compo_number}} ] } ).limit(pagesize).skip(skip) allcount = cursor.count()
注意要将 limit函数 放在 skip函数以前,这样可以避免在数据量很大的时候引起的skip性能问题。性能
但有时不仅要find查找,还要进行数据的聚合(相似于mysql里的连表查询),此时返回的是commandcursor对象,没有limit与skip函数可用了,这个时候就必须使用mongo的修改器:优化
形如:命令行
countagg = db.compo_message.aggregate([ { "$lookup": { "from": "extracted_result", "localField": "_id", "foreignField": "_id", "as": "result" } }, { "$match": { "上传人":updateuser, "$and":[ {"上传时间":{"$regex":updatetime}}, {"公司":{"$regex":company}}, {"元件类型":{"$regex":component_type}}, {"元件号":{"$regex":compo_number}} ] } }, { "$group": { "_id" : None, "count":{"$sum":1} } } ]) countlist = list(countagg) if countlist: allcount = countlist[0].get('count') else: allcount = 0 cursor = db.compo_message.aggregate([ { "$lookup": { "from": "extracted_result", "localField": "_id", "foreignField": "_id", "as": "result" } }, { "$match": { "上传人":updateuser, "$and":[ {"上传时间":{"$regex":updatetime}}, {"公司":{"$regex":company}}, {"元件类型":{"$regex":component_type}}, {"元件号":{"$regex":compo_number}} ] } }, { "$skip": skip }, { "$limit": pagesize } ])
在使用修改器的时候,mongo内部对limit和skip进行了优化。code
相对于find查找而言,聚合的操做效率就要低不少了,表间链接查询很是频繁的话,这块可能会成为瓶颈。component