使用mongo做分页查询
我使用的是pymongo,pymongo的函数库非常接近mongo的原生命令行。
在使用普通的find查找的时候,可以使用pymongo的limit与skip函数
形如:
1cursor = db.compo_message.find( 2 { 3 "上传人":updateuser, 4 "$and":[ 5 {"上传时间":{"$regex":updatetime}}, 6 {"公司":{"$regex":company}}, 7 {"元件类型":{"$regex":component_type}}, 8 {"元件号":{"$regex":compo_number}} 9 ] 10 } 11).limit(pagesize).skip(skip) 12 13allcount = cursor.count()
注意要将 limit函数 放在 skip函数之前,这样能够避免在数据量很大的时候引发的skip性能问题。
但有时不只要find查找,还要进行数据的聚合(类似于mysql里的连表查询),此时返回的是commandcursor对象,没有limit与skip函数可用了,这个时候就必须使用mongo的修改器:
形如:
1countagg = db.compo_message.aggregate([ 2 { 3 "$lookup": 4 { 5 "from": "extracted_result", 6 "localField": "_id", 7 "foreignField": "_id", 8 "as": "result" 9 } 10 }, 11 { 12 "$match": 13 { 14 "上传人":updateuser, 15 "$and":[ 16 {"上传时间":{"$regex":updatetime}}, 17 {"公司":{"$regex":company}}, 18 {"元件类型":{"$regex":component_type}}, 19 {"元件号":{"$regex":compo_number}} 20 ] 21 } 22 23 }, 24 { 25 "$group": 26 { 27 "_id" : None, 28 "count":{"$sum":1} 29 } 30 } 31]) 32 33countlist = list(countagg) 34 35if countlist: 36 allcount = countlist[0].get('count') 37else: 38 allcount = 0 39 40cursor = db.compo_message.aggregate([ 41 { 42 "$lookup": 43 { 44 "from": "extracted_result", 45 "localField": "_id", 46 "foreignField": "_id", 47 "as": "result" 48 } 49 }, 50 { 51 "$match": 52 { 53 "上传人":updateuser, 54 "$and":[ 55 {"上传时间":{"$regex":updatetime}}, 56 {"公司":{"$regex":company}}, 57 {"元件类型":{"$regex":component_type}}, 58 {"元件号":{"$regex":compo_number}} 59 ] 60 } 61 62 }, 63 { "$skip": skip }, 64 { "$limit": pagesize } 65])
在使用修改器的时候,mongo内部对limit和skip进行了优化。
相对于find查找而言,聚合的操作效率就要低很多了,表间连接查询非常频繁的话,这块可能会成为瓶颈。