0

館藏結構組收集數據的MongoDB

Order = new Schema 
    index:   { type: Number, unique: true } 
    number:   Date 
    status:   { type: String, enum: ['success', 'failure'] } 
    created_at:  { type: Date, default: Date.now } 
    updated_at:  { type: Date, default: Date.now } 

我需要返回我有數據,成功次數和失敗對象的數組計數按日期分組查詢幫助。 EX-

orders = { 
       28-10-2016:{ 
       success_count: 10, 
       failure_count: 10 
       }, 
       29-10-2016: { 
       success_count: 10, 
       failure_count: 10 
       } 
      } 
+0

請張貼在這裏,你已經嘗試到目前爲止 –

+0

@ClementAmarnath不鼓勵OP的意見後的代碼是什麼,這是難以閱讀。相反,請使用[編輯]鏈接更新包含其他信息的問題。 – chridam

+0

@chridam我想讓他發佈有問題的代碼,而不是在評論中,可能在我的評論中沒有正確傳達給他:-) –

回答

4

隨着聚合框架,其結果將是從「期望」的輸出,而不必哈希鍵略有不同,你得到的對象與代表你的_id鍵具有值數組按字段分組。例如,而不是

{ 
    "28-10-2016":{ 
     "success_count": 10, 
     "failure_count": 10 
    }, 
    "29-10-2016": { 
     "success_count": 10, 
     "failure_count": 10 
    } 
} 

你不得不喜歡

[ 
    { 
     "_id": "28-10-2016", 
     "success_count": 10, 
     "failure_count": 10 
    }, 
     "_id": "29-10-2016", 
     "success_count": 10, 
     "failure_count": 10 
    } 
] 

更好的結構實現上述結果將需要使用$cond運營商在$sum累加器操作。運算符將根據其第一個參數(if)評估邏輯條件,然後返回評估爲true的第二個參數(then)或第三個參數爲false(else)。此真/假邏輯轉換成1個0,其分別送入$sum數值:

"success_count": { 
    "$sum": { 
     "$cond": [ { "$eq": [ "$status", "success" ] }, 1, 0 ] 
    } 
} 

作爲所得管道,一個需要運行它使用$dateToString操作者在_id的聚合操作爲$group管道關鍵表達式:

Orders.aggregate([ 
    { 
     "$group": { 
      "_id": { 
       "$dateToString": { 
        "format": "%Y-%m-%d", 
        "date": "$created_at" 
       } 
      }, 
      "success_count": { 
       "$sum": { 
        "$cond": [ { "$eq": [ "$status", "success" ] }, 1, 0 ] 
       } 
      }, 
      "failure_count": { 
       "$sum": { 
        "$cond": [ { "$eq": [ "$status", "failure" ] }, 1, 0 ] 
       } 
      } 
     } 
    } 
], function (err, orders){ 
    if (err) throw err; 
    console.log(orders); 
}) 

但是,它的執行速度比上面,在那裏爲您彙總結果的最有效的數據結構如下例如架構更快更靈活和更高性能的方法:

orders = [ 
    { 
     "_id": "28-10-2016", 
     "counts": [ 
      { "status": "success", "count": 10 }, 
      { "status": "failure", "count": 10 } 
     ] 
    }, 
    { 
     "_id": "29-10-2016", 
     "counts": [ 
      { "status": "success", "count": 10 }, 
      { "status": "failure", "count": 10 } 
     ] 
    } 
] 

然後考慮運行的替代管道如下

Orders.aggregate([ 
    { 
     "$group": { 
      "_id": { 
       "date": { 
        "$dateToString": { 
         "format": "%Y-%m-%d", 
         "date": "$created_at" 
        } 
       }, 
       "status": { "$toLower": "$status" } 
      }, 
      "count": { "$sum": 1 } 
     } 
    }, 
    { 
     "$group": { 
      "_id": "$_id.date", 
      "counts": { 
       "$push": { 
        "status": "$_id.status", 
        "count": "$count" 
       } 
      } 
     } 
    } 
], function (err, orders){ 
    if (err) throw err; 
    console.log(orders); 
}) 
+0

這正是我想要的。謝謝@chridam! –