mongo实现分页模糊查询

使用mongo做分页查询

我使用的是pymongo,pymongo的函数库非常接近mongo的原生命令行。

在使用普通的find查找的时候,可以使用pymongo的limit与skip函数

形如:

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进行了优化。

相对于find查找而言,聚合的操作效率就要低很多了,表间连接查询非常频繁的话,这块可能会成为瓶颈。

评论

暂无评论