首页 > 解决方案 > 将文档列表设置为变量后的pymongo排序

问题描述

我最近发现我的代码中的 .sort() 被我的其他代码打断了。我想列出 30 天内发布的一组文档,并按最喜欢的顺序对其进行排序。之前的工作是一直查找所有文档,所以我的代码已经用喜欢排序,然后我添加了句点。

问题是我的列表是按日期内的喜欢排序的。例如,最喜欢的文档列在不太喜欢的文档下,该文档有一些喜欢但发布的日期较新。

这是我的代码

@app.route('/api/list/monthly_hot', methods=['GET'])
def show_monthly_hot():
    fmt = "%Y-%m-%d"
    today = datetime.now(timezone('Asia/Seoul'))
    all = list(db.collection.find({}, {'_id': False}).sort('like', -1))
    hot_posts = []
    for i in range(0, 30):
        target = today - timedelta(days=i)
        period = target.strftime(fmt)
        for x in all:
            if x['date'] == period:
                y = x
                hot_posts.append(y)
    return jsonify({'hot_posts': hot_posts})

所以我试图把 .sort() 放在不同的变量中

@app.route('/api/list/monthly_hot', methods=['GET'])
def show_monthly_hot():
    fmt = "%Y-%m-%d"
    today = datetime.now(timezone('Asia/Seoul'))
    all = list(db.collection.find({}, {'_id': False}).sort('like', -1))
    hot_posts = [].sort('like', -1)
    for i in range(0, 30):
        target = today - timedelta(days=i)
        period = target.strftime(fmt)
        for x in all:
            if x['date'] == period:
                y = x.sort('like', -1)
                hot_posts.append(y).sort('like', -1)
    return jsonify({'hot_posts': hot_posts}).sort('like', -1)

= 失败(一次尝试一个,而不是像上面的所有行)

我试过如何按字典的值对字典列表进行排序?

@app.route('/api/list/monthly_hot', methods=['GET'])
def show_monthly_hot():
    fmt = "%Y-%m-%d"
    today = datetime.now(timezone('Asia/Seoul'))
    all = list(db.collection.find({}, {'_id': False}).sort('like', -1))
    hot_posts = []
    for i in range(0, 30):
        target = today - timedelta(days=i)
        period = target.strftime(fmt)
        for x in all:
            if x['date'] == period:
                y = sorted(x, key=itemgetter('like'), reverse=True)
                hot_posts.append(y)
    return jsonify({'hot_posts': hot_posts})

= 失败

标签: pythonmongodbsortingfor-looppymongo

解决方案


推荐阅读