python - 将文档列表设置为变量后的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})
= 失败
解决方案
推荐阅读
- twitter-bootstrap - Bootstrap 4.1 固定 div 溢出-y 和全宽
- javascript - 如何在 ES6 中使用 spread(...)?
- javascript - javascript:在函数中获取未破坏的参数
- arrays - 以数组形式提供的字符串输出调整 // -NODE JS-
- javascript - React - 如何将参数传递给事件处理程序
- java - 在处理过程中,Exchange 的属性正在与 ArrayList<> 同步更新
- c++ - 在 .text 部分定义只读数据的原因是什么?
- angular - Angular4 - 有没有办法使指令透明?
- javascript - 如何同时停止传播和允许模态?
- android - xamarin android 开始阻塞 GC eXPLICIT?