Python Pymongo按降序排序注释
在一个小型博客应用程序中,我想按照日期降序排列评论。最新评论将在顶部 典型的帖子如下所示:Python Pymongo按降序排序注释,python,mongodb,pymongo,Python,Mongodb,Pymongo,在一个小型博客应用程序中,我想按照日期降序排列评论。最新评论将在顶部 典型的帖子如下所示: { "_id" : 15, "title" : "Soup making techniques", "content" : "In this tutorial we'd like to share best soup making practices.", "updatedate" : ISODate("2017-10-19T21:13:19.193Z"), "co
{
"_id" : 15,
"title" : "Soup making techniques",
"content" : "In this tutorial we'd like to share best soup making practices.",
"updatedate" : ISODate("2017-10-19T21:13:19.193Z"),
"comments" : [
{
"content" : "This is my first comment.",
"_id" : 25,
"date" : ISODate("2017-10-19T21:13:31.328Z")
},
{
"content" : "Another comment.",
"_id" : 26,
"date" : ISODate("2017-10-19T21:29:36.536Z")
}
]
}
同样在python方面,相关代码如下所示
post = document.find_one({'_id': int(number)}, sort=[("comments.date", -1)])
result = document.find_one( { '_id' : int(number) , "comments": { '$exists': True, '$ne': False } })
comments = []
commentlist = []
if result:
commentlist = post['comments']
print ("All comments", commentlist)
for comment in commentlist:
comments.append({'commentid' : comment['_id'], 'date' : comment['date'], 'content' : comment['content']})
关于您发布的模式设计,有两件事值得一提:
$position
修饰符的$push
来实现(请参阅)