2013-11-20 37 views
2

我有以下的收集和:MongoDB的順序由上一個子集

error_reports 
[  
    { 
     "_id":{ 
      "$oid":"5184de1261" 
     }, 
     "date":"29/04/2013", 
     "errors":[ 
      { 
      "_id":"10", 
      "failures":2, 
      "alerts":1, 
      }, 
      { 
      "_id":"11", 
      "failures":7, 
      "alerts":4, 
      } 
     ] 
    }, 
    { 
     "_id":{ 
      "$oid":"5184de1262" 
     }, 
     "date":"30/04/2013", 
     "errors":[ 
      { 
      "_id":"15", 
      "failures":3, 
      "alerts":2, 
      }, 
      { 
      "_id":"16", 
      "failures":9, 
      "alerts":1, 
      } 
     ] 
    } 
] 

是否有可能通過檢索降序排序的失敗與失誤和警報和文件清單?我是新來的MongoDB,我已經2天尋找,但我無法弄清楚什麼是正確的查詢......

我想是這樣的:

db.error_reports.aggregate(
    { $sort : { failures: -1} }, 
    { $group: 
     { _id: "$_id", 
     failures: { "$sum": "$errors.failures" } 
     } 
    } 
); 

但事與願違工作中,我認爲這是因爲$sum$errors.failures的事情,我想總結的day_hours子集合的每一個項目這個屬性,但我不知道在查詢中做到這一點...

回答

5

你是與你的嘗試非常接近。唯一缺少的是$unwind aggregation operator$unwind基本上基於子文檔將每個文檔分割出來。所以你組之前的失誤和警報,你放鬆的錯誤,像這樣:

db.error_reports.aggregate(
    { $unwind : '$errors' }, 
    { $group : { 
    _id : '$_id', 
    'failures' : { $sum : '$errors.failures' }, 
    'alerts' : { $sum : '$errors.alerts' } 
    } }, 
    { $sort : { 'failures': -1 } } 
); 

,讓你後續的結果:

{ 
    "result" : [ 
     { 
      "_id" : ObjectId("5184de1262"), 
      "failures" : 12, 
      "alerts" : 3 
     }, 
     { 
      "_id" : ObjectId("5184de1261"), 
      "failures" : 9, 
      "alerts" : 5 
     } 
    ], 
    "ok" : 1 
} 
+0

非常感謝你,這正是我需要的。我不知道有這樣一個運營商。 – Sanduckhan