2017-10-19 119 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/