您如何对聚合管道的输出进行分页?

时间:2019-09-20 11:16:41

标签: mongodb flask pymongo

我正在尝试为博客撰写一系列帖子。我有一个管道,可以很好地输出帖子,我正在尝试使用facet来分页结果。跳过和限制有效,但是当我将带有http://localhost:5000/?page=4的URL中的页码传递到管道中时,没有任何变化。我仍然只收到前5个帖子(或我设置的上限不多)

def posts_with_comment_count(page):

    pipeline = [
        {"$lookup": {
            "from": "comment",
            "localField": "_id",
            "foreignField": "post_id",
            "as": "comment_count"
        }},
        {"$addFields": {
            "comment_count": {"$size": "$comment_count"}
        }},
        {"$sort": {"_id": -1}}, 
        {'$facet': { 
            "metadata": [{"$count": "total"}, {"$addFields": {"page": int(page)}}],
            "data": [{"$skip": 0}, {"$limit": 5}] 
            }}

    ]
    posts = list(mongo.db.posts.aggregate(pipeline))
    return posts


@app.route("/")
@app.route("/home")
@app.route("/index")
def home():

    page = request.args.get('page', 1, type=int)   
    data = posts_with_comment_count(page)

    def posts():
     for post in data:
        return post['data']

    return render_template('home.html', posts=posts())

0 个答案:

没有答案