2012-01-20 46 views
2

我正在嘗試使用Mongo進行一些測試,我已經找到了一些更簡單的MySQL查詢Mongo等價物。MongoDB - MySQL SUM(CASE WHEN)等價嗎?

我有這個疑問這是一個有點複雜,我需要幫助...

SELECT DISTINCT dims_user, 
    COUNT(DISTINCT asset_name) AS asset_count, 
    COUNT(DISTINCT system_name) AS station_count, 
    SUM(CASE WHEN details ='viewed' then 1 Else 0 end) AS viewed_count, 
    SUM(CASE WHEN details Like 'Viewed Web%' then 1 Else 0 end) AS Web_count, 
    SUM(CASE WHEN details = 'ThumbView' then 1 Else 0 end) AS ThumbView_count, 
    SUM(CASE WHEN details Like 'Exported%' then 1 Else 0 end) AS Exported_count, 
    SUM(CASE WHEN details Like '%Print%' then 1 Else 0 end) AS Printed_count 
FROM asset_log GROUP BY dims_user; 
+1

呃......這不是很好的關係練習......「細節」列中的數據應該標準化 - 對於NoSQL db設計也是如此,column:action =(view | web | thumb | export | print),那麼你只需切換到一個組。 – Rudu

+0

它的一堆日誌文件,我剛剛得到了什麼有32萬條記錄 – rreeves

+2

然後[ETL](http://en.wikipedia.org/wiki/Extract,_transform,_load)它一次(如果它是靜態的 - 或建立一個加載/轉換過程用於重複加載),以便它被標準化。這將大大簡化你想要做的事情。 – Rudu

回答

1

我會Rudu這裏達成協議,你應該嘗試打破細節到蒙戈文件的密鑰。

該文件可能包含一個對象是這樣的:

details: 
{ 
    viewed: true 
    thumb_view: true 
    web_viewed: false 
    exported: true 
    ... 
} 

如果不重組的數據,查詢需要無根的正則表達式無法使用的MongoDB的索引功能。

但是,無論您是否決定這麼做,您都會希望使用map reduce。您可以在地圖期間發出包含詳細信息的項目(通過使用正則表達式處理它們,或者簡單地以重新構造的形式發出鍵)並在縮小階段對它們進行求和。

你可以閱讀更多關於它的docs

1

可能在下面的示例中對您有用。

假設您有以下示例數據。

db.sample.insert([ 
{ 
    "_id" : 27001, 
    "assigned_to" : "[email protected]", 
    "priority" : "High" 
} 
,{ 
    "_id" : 27002, 
    "assigned_to" : "[email protected]", 
    "priority" : "Low" 
}, 
{ 
    "_id" : 27003, 
    "assigned_to" : "[email protected]", 
    "priority" : "High" 
} 
]); 

使用下面彙總查詢來獲取

1.Total計數

2.Count其中assigend_to是 「[email protected]

3.Count其中優先級爲「高「

db.sample.aggregate({$group:{ 
           _id: 0,total:{$sum:1}, 
           'assigned_to' : { $sum : { $cond: [ { $eq: [ '$assigned_to' , '[email protected]' ] }, 1, 0 ] } }, 
           'hight_priority' : { $sum : { $cond: [ { $eq: [ '$priority' , 'High' ] }, 1, 0 ] } } 
           } 
         } 
        ); 

,你會得到預期的結果

{ 
    "result" : [ 
     { 
      "_id" : 0, 
      "total" : 3, 
      "assigned_to" : 2, 
      "hight_priority" : 2 
     } 
    ], 
    "ok" : 1 
}