2014-11-21 166 views
-2

我需要將下面的mysql查詢轉換爲mongo。 任何幫助將不勝感激。MySQL到MongoDB查詢翻譯

 SELECT cr.*, COUNT(cj.job_id) AS finished_chunks FROM `checks_reports_df8` cr 
     LEFT JOIN `checks_jobs_df8` cj ON cr.id = cj.report_id 
     WHERE cr.started IS NOT NULL AND cr.finished IS NULL AND cj.is_done = 1 

回答

1

MongoDB不做JOIN。所以你將不得不查詢這兩個集合並在應用層上執行JOIN。如何做到這一點完全取決於您使用哪種編程語言來開發應用程序。你不會說你使用哪一個,所以我只給你一個JavaScript例子。當你使用不同的語言:第二個片段只是一個簡單的FOR循環。

這些是您要使用的MongoDB查詢。我無法訪問您的數據,因此我無法保證正確性。

var reports = db.checks_reports_df8.find({ 
     "started": {$exists: 1 }, 
     "finished": {$exists: 0 } 
}); 

此查詢假定您的空值由缺少的字段表示,這是MongoDB中的常規做法。當您有實際的null值時,請使用"started": { $ne: null }"finished": null

然後迭代您獲得的文檔數組。對於每個RESULT執行此查詢:

reports.forEach(function(report) { 

    var job_count = db.checks_jobs_df8.aggregate([ 
     {$match: { 
      "report_id": report.id, 
      "is_done": 1 
     }}, 
     {$group: { 
      _id: "$job_id", 
      "count": { $sum: 1 } 
     }} 
    ]) 

    // output the data from report and job_count here 

}); 
+0

謝謝@Philipp。這正是我需要的。順便提一下,Python的語言是Python。但是很容易適應你的答案。謝謝! – 2014-11-25 10:15:43