2015-06-25 28 views
2

我曾文件名爲question我如何排序字段陣列的MongoDB的文檔

var QuestionSchema = new Schema({ 
    title: { 
     type: String, 
     default: '', 
     trim: true 
    }, 
    body: { 
     type: String, 
     default: '', 
     trim: true 
    }, 
    user: { 
     type: Schema.ObjectId, 
     ref: 'User' 
    }, 
    category: [], 
    comments: [{ 
     body: { 
      type: String, 
      default: '' 
     }, 
     root: { 
      type: String, 
      default: '' 
     }, 
     user: { 
      type: Schema.Types.ObjectId, 
      ref: 'User' 
     }, 
     createdAt: { 
      type: Date, 
      default: Date.now 
     } 
    }], 
    tags: { 
     type: [], 
     get: getTags, 
     set: setTags 
    }, 
    image: { 
     cdnUri: String, 
     files: [] 
    }, 
    createdAt: { 
     type: Date, 
     default: Date.now 
    } 
}); 

其結果是,我需要通過根字段進行排序comments,這樣 example

我試過內在後臺手動排序comments的數組並嘗試使用聚合,但我無法對此進行排序。請幫助。

+2

您可以請[**編輯**](http://stackoverflow.com/posts/31048478/edit)您的問題向我們展示您迄今爲止所嘗試的內容,就您提到的聚合管道而言,你能包括你期望的輸出的實際代碼,而不是嵌入鏈接,因爲我們想重現相同的問題並幫助你解決它。 – chridam

回答

3

。假定Question是在你的代碼模型對象,當然,你要排序您從createdAt日期‘「的評論’,然後使用.aggregate()你這樣做:

Question.aggregate([ 
    // Ideally match the document you want 
    { "$match": { "_id": docId } }, 

    // Unwind the array contents 
    { "$unwind": "comments" }, 

    // Then sort on the array contents per document 
    { "$sort": { "_id": 1, "comments.createdAt": 1 } }, 

    // Then group back the structure 
    { "$group": { 
     "_id": "$_id", 
     "title": { "$first": "$title" }, 
     "body": { "$first": "$body" }, 
     "user": { "$first": "$user" }, 
     "comments": { "$push": "$comments" }, 
     "tags": { "$first": "$tags" }, 
     "image": { "$first": "$image" }, 
     "createdAt": { "$first": "$createdAt" } 
    }} 
], 
function(err,results) { 
    // do something with sorted results 
}); 

但是, 。實在是大材小用,因爲文檔間你是不是「聚集」只需使用JavaScript的方法,而不是如.sort()

Quesion.findOneById(docId,function(err,doc) { 
    if (err) throw (err); 
    var mydoc = doc.toObject(); 
    mydoc.questions = mydoc.questions.sort(function(a,b) { 
     return a.createdAt > b.createdAt; 
    }); 
    console.log(JSON.stringify(doc, undefined, 2)); // Intented nicely 
}); 

因此,儘管MongoDB確實在服務器上具有「工具」,但在檢索數據時,最好在客戶端代碼中執行此操作,除非實際需要「聚合」文檔。

但現在已經給出了兩個示例用法。

+1

+1爲「在客戶端做」或至少不在Mongo中。當你想要處理多個文檔時,你應該使用聚合,例如,獲得網站上的最後100條評論 –

+0

@ stephane-ruhlmann是的,這點在這裏非常感謝你得到它。太多人認爲「NoSQL」方式僅僅是他們從「SQL方式」中選取的「壞蛋」的延伸。事實上,即使在RDBMS中,它們確實適合(或不適用)他們的目的,但他們「從未這樣做」的方式從未如此。只是試圖指出什麼是正確的,如你所說的「在客戶端」似乎是這裏是正確的案例。 –

+0

偉大的總結,沒有什麼補充! –