Python 如何获取Mongo聚合的分页

Python 如何获取Mongo聚合的分页,python,mongodb,flask,pymongo,Python,Mongodb,Flask,Pymongo,我一直在使用flask paginate进行分页,并将Mongo DB用作数据库: 在view.py页面中 from flask_paginate import Pagination, get_page_args @app.route('/test',methods=['GET','POST']) def searchindex(): page, per_page, offset = get_page_args() pipeline = [{ '$match': {

我一直在使用flask paginate进行分页,并将Mongo DB用作数据库:

在view.py页面中

from flask_paginate import Pagination, get_page_args

@app.route('/test',methods=['GET','POST'])
def searchindex():
    page, per_page, offset = get_page_args()
    pipeline = [{
    '$match': {
       "meanings.speech_part":word_type,
       "$expr": { "$gt": [ { "$strLenCP": "$word" }, word_length ] }
    }}]
    cursor_objects = db['test'].aggregate(pipeline)
    cursor_objects_list=list(cursor_objects)
    pagination = Pagination(page=page, total=len(cursor_objects_list),per_page=per_page,offset=offset,record_name='words')
    return render_template('index.html',data=cursor_objects_list,pagination=pagination)
在index.html中:

{{ pagination.info }}
{{ pagination.links }}

{% for word in data %}
  <tr>
    <td>{{ loop.index + pagination.skip }}</td>
    <td> {{ word['word'] }}</td>
  </tr>
{% endfor %}
{{pagination.info}
{{pagination.links}
{数据%中的字的百分比}
{{loop.index+pagination.skip}
{{word['word']}
{%endfor%}
当我这样做时,所有结果立即显示为:

即使单击
2
(第2页)也会显示相同的结果,但数字范围更改为:

我被困在我做错了的地方,
限额
是否适用于总量是我头上的问题


感谢您的帮助,TIA

建议您使用
$sort
运算符进行正确分页

可能每次执行都会得到不同的结果

试试MongoDB的方式。只需将最后阶段
$skip
$limit
添加到聚合管道(假设您有>1M条记录),然后分别计算总结果:

#We add $skip and $limit
pipeline = [
  {
    '$match': {
       "meanings.speech_part":word_type,
       "$expr": { "$gt": [ { "$strLenCP": "$word" }, word_length ] }
    }
  },
  {'$sort': {'_id': 1}},
  {'$skip': page * per_page},
  {'$limit': per_page}
]

#We add $count
count_pipeline = [
  {
    '$match': {
       "meanings.speech_part":word_type,
       "$expr": { "$gt": [ { "$strLenCP": "$word" }, word_length ] }
    }
  },
  {'$count': "total"}
]
现在,我们计算没有
$skip
$limit
的总记录,也没有
$sort

pagination = Pagination(page=page, total=list(db['test'].aggregate(count_pipeline))[0].total, per_page=per_page, offset=offset, record_name='words')
return render_template('index.html', data=cursor_objects_list, pagination=pagination)

我应该包括数据格式吗,这是一个简单的json,对于collectionfor skip中的所有文档都是一样的。我们可以使用偏移量,尽管我无法获得正确的分页,但当我进行合计时,它显示错误为:类“int”未定义“getitem”,因此“[]”运算符不能用于其实例请再次检查,应该使用
list
而不是
len
@Codenewbie我很高兴能帮助你:-)