2017-10-19 118 views
1

在一个小博客应用程序中,我想根据日期降序排列评论。最新的评论将是最高的。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"), 
    "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") 
     } 
    ] 
} 

而且对蟒蛇侧的相关代码如下所示;

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']}) 

回答

1

有一个价值几件事情是关于架构设计你贴提的是:

  1. 如果一个职位有很多长的意见,也可以振振有词超过16 MB的大小,这是MongoDB文档的大小限制。
  2. 将注释放入数组很难排序,正如您发现的那样。

您发布的Python脚本被迫提取comments数组并将它们逐个插入到临时文档中,以便将其按排序顺序排列。我不认为这种方法将是高性能的。您至少有几个选项可以避免这样做:

  1. 在数组的开头插入一个新注释,以便数组总是按降序排序。这可以通过使用$push$position修改器实现(请参阅https://docs.mongodb.com/manual/reference/operator/update/push/
  2. 将注释放在单独的集合上,并参考原始帖子。这使得它易于排序,并且可以进行相对更复杂的检索(但它不会比当前的脚本更糟糕)。

根据您的使用情况,选项1,2或两者都可能适用于您。

您可能还想看看存储评论用例:https://docs.mongodb.com/ecosystem/use-cases/storing-comments/