2

我正在使用烧瓶分页(仅供参考)在烧瓶(Python框架)中进行分页

我能够find为以下查询实现分页:

from flask_paginate import Pagination
from flask_paginate import get_page_args

def starting_with_letter(letter):
    page, per_page, offset = get_page_args()
    collection_name=letter.lower()+'_collection'
    words=db[collection_name]
    data_db=words.find()
    data=data_db.limit(per_page).skip(offset) '''Here I have achieved the limit and skip'''
    pagination = Pagination(page=page, total=data.count(),per_page=per_page,offset=offset,record_name='words')
    return render_template('startingwords.html',data=data,pagination=pagination)

但我不能在这里对聚合做同样的事情:

def test():
    page, per_page, offset = get_page_args()
    cursor_list=[]  '''appending each cursor in iteration of for loop '''
    collections=db.collection_names()
    for collection in collections:
        cursor_objects = db[collection].aggregate([
                {
                    "$match": {
                        "$expr": {"$eq": [{"$strLenCP": "$word"}, 6]}
                    }
                },
                            {"$skip": offset},    
                            {"$limit": per_page}

            ])
        for cursor in cursor_objects:
            cursor_list.append(cursor)
    pagination = Pagination(page=page, total=len(cursor_list),per_page=per_page,offset=offset,record_name='words')
    return render_template('lettersearch.html',data=cursor_list,pagination=pagination)

结果显示为:

在此处输入图像描述

这里所有的39结果都显示在单页上

击中page 2它显示:

在此处输入图像描述

注意:默认情况下,flask-paginate 最初设置per_page为 as10offsetas0

在参考了许多我尝试过的链接之后:

放置skiplimit以上match任何方式都是错误的

还学到了limit总是跟在后面skip

我坚持这一点,任何帮助表示赞赏

4

1 回答 1

1

你的问题不在于skip()and limit(); 那工作正常。问题在于您的整体逻辑;您在第一个循环中迭代所有 39 个集合,然后将聚合的每个结果附加到cursor_list.

我无法弄清楚您要做什么的逻辑,因为第一个示例是在单词集合中查找,第二个示例是在所有集合中查找单词字段;话虽如此,您可能会简化您的方法,例如:

offset = 0
per_page = 10
collections = db.list_collection_names()
#
# Add some logic on the collections array to filter what is needed 
#
print(collections[offset:offset+per_page])

编辑以反映评论。执行此操作的函数的完整示例。不需要聚合查询——这增加了复杂性。

from pymongo import MongoClient
from random import randint

db = MongoClient()['testdatabase1']

# Set up some data
for i in range(39):
    coll_name = f'collection{i}'
    db[coll_name].delete_many({}) # Be careful; testing only; this deletes your data
    for k in range (randint(0, 2)):
        db[coll_name].insert_one({'word': '123456'})

# Main function
def test(offset, per_page, word_to_find):
    found = []
    collections = db.list_collection_names()
    for collection in sorted(collections):
        if db[collection].find_one({word_to_find: { '$exists': True}}) is not None:
            found.append(collection)

    print(found[offset:offset+per_page])

test(offset=0, per_page=10, word_to_find='word')
于 2020-01-03T12:02:22.353 回答