在一个小的博客应用程序中,我想按日期降序排列评论。最新评论将排在前面。你知道吗
典型的帖子是这样的:
{
"_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']})
关于您发布的架构设计,有几点值得一提:
您发布的Python脚本被迫提取comments数组,并将它们逐个插入到临时文档中,以使其按排序顺序排列。我认为这种方法不会奏效。您至少有几个选项可以避免这样做:
$push
和$position
修饰符来实现(参见https://docs.mongodb.com/manual/reference/operator/update/push/)根据您的用例,选项1、2或两者都可能适用于您。你知道吗
您可能还想看看存储注释用例:https://docs.mongodb.com/ecosystem/use-cases/storing-comments/
相关问题 更多 >
编程相关推荐