2014-06-11 60 views
7

我有一系列的文件(查看事件)在MongoDB中看起來像這樣:集團通過條件MongoDB中

{ 
    "_id" : ObjectId("5397a78ab87523acb46f56"), 
    "inspector_id" : ObjectId("5397997a02b8751dc5a5e8b1"), 
    "status" : 'defect', 
    "utc_timestamp" : ISODate("2014-06-11T00:49:14.109Z") 
} 

{ 
    "_id" : ObjectId("5397a78ab87523acb46f57"), 
    "inspector_id" : ObjectId("5397997a02b8751dc5a5e8b2"), 
    "status" : 'ok', 
    "utc_timestamp" : ISODate("2014-06-11T00:49:14.109Z") 
} 

我需要得到一個結果集,看起來像這樣:

[ 
    { 
    "date" : "2014-06-11", 
    "defect_rate" : '.92' 
    }, 
    { 
    "date" : "2014-06-11", 
    "defect_rate" : '.84' 
    }, 
] 

換句話說,我需要得到每天的平均缺陷率。這可能嗎?

回答

12

聚集框架是你想要什麼:

db.collection.aggregate([ 
    { "$group": { 
     "_id": { 
      "year": { "$year": "$utc_timestamp" }, 
      "month": { "$month": "$utc_timestamp" }, 
      "day": { "$dayOfMonth": "$utc_timestamp" }, 
     }, 
     "defects": { 
      "$sum": { "$cond": [ 
       { "$eq": [ "$status", "defect" ] }, 
       1, 
       0 
      ]} 
     }, 
     "totalCount": { "$sum": 1 } 
    }}, 
    { "$project": { 
     "defect_rate": { 
      "$cond": [ 
       { "$eq": [ "$defects", 0 ] }, 
       0, 
       { "$divide": [ "$defects", "$totalCount" ] } 
      ] 
     } 
    }} 
]) 

所以首先你組當天使用date aggregation operators並獲得某一天的項目TOTALCOUNT。這裏使用$cond運算符確定「狀態」是否實際上是缺陷,結果是隻有「缺陷」值被計數的條件$sum

一旦這些分組每天你只需$divide的結果,與$cond另一個檢查,以確保你沒有被零除。

+0

感謝發佈!有道理,但它不在MongoDB控制檯中運行。沒有錯誤消息,我試圖通過,看看它是否是一個語法的東西...... – okoboko

+0

你只是複製和粘貼? 「收藏」需要是你收藏的名字。這只是我使用的基本名稱,除非您實際指定了您在問題中嘗試過的查詢。 –

+0

是的,我改變了我的查詢。 – okoboko