2016-12-05 44 views
2

我有一個mongo集合,其中包含各自具有困難的問題。MongoDB限制條件

我想要做的是根據爲每個問題難度配置的金額查詢集合。所以說我有三個難度級別,1(easy,2(medium),3(hard),我已經配置了我的應用程序,以便在總共50個問題中抽取15個簡單,15箇中等和20個難度。

什麼是彙總這些數據的最佳方式是什麼?到目前爲止,我有沒有運氣與$match$cond似乎並不能有條件限制$in操作爲好。

+0

請將您嘗試過的內容添加到帖子中,並添加樣本文檔以進行測試。 – Veeram

+0

我試過的是不相關的,因爲你不能使用'$ match($ in ... $ limit)'作爲mongo,這正是我所希望的。用於測試的文檔可以是任意的,只需具有難度爲「關鍵字」的文檔並且值範圍從1-3,例如'{「difficuty」:Number(1)}',但我並不認爲這是相關的信息。 – Syx

回答

3

讓我們看看你有以下的文檔結構

{ "_id" : ObjectId("5845ad672324699ec94a5399"), "difficulty" : 1 } 
{ "_id" : ObjectId("5845ad692324699ec94a539a"), "difficulty" : 2 } 
{ "_id" : ObjectId("5845ad6b2324699ec94a539b"), "difficulty" : 3 } 
{ "_id" : ObjectId("5845ad6c2324699ec94a539c"), "difficulty" : 3 } 
{ "_id" : ObjectId("5845ad702324699ec94a539d"), "difficulty" : 2 } 
{ "_id" : ObjectId("5845ad722324699ec94a539e"), "difficulty" : 1 } 
{ "_id" : ObjectId("5845ad732324699ec94a539f"), "difficulty" : 1 } 
{ "_id" : ObjectId("5845ad742324699ec94a53a0"), "difficulty" : 1 } 
{ "_id" : ObjectId("5845ad762324699ec94a53a1"), "difficulty" : 2 } 
{ "_id" : ObjectId("5845ad762324699ec94a53a2"), "difficulty" : 2 } 
{ "_id" : ObjectId("5845ad782324699ec94a53a3"), "difficulty" : 3 } 

現在你想拉15 easy, 15 medium, and 20 hard for a total of 50 questions所以這個首先應該創建組difficulty和使用$condprojectslice陣列根據您的計數。請選擇以下查詢:

db.difficulty.aggregate({ "$match": { "difficulty": { "$in": [1, 2, 3] } } }, 
     { "$group": { "_id": "$difficulty", "data": { "$push": "$$ROOT" } } }, { 
    "$project": { 
     "result": { 
      "$cond": { 
       "if": { "$eq": [1, "$_id"] }, 
       "then": { "easy": { "$slice": ["$data", 15] } }, //15 for easy 
       "else": { 
        "$cond": { 
         "if": { "$eq": [2, "$_id"] }, 
         "then": { "medium": { "$slice": ["$data", 15] } },// 15 for medium 
         "else": { "hard": { "$slice": ["$data", 20] } } // 20 for hard 
        } 
       } 
      } 
     } 
    } 
}).pretty() 
+0

我收到一個關於缺少'else'的錯誤,當我添加一個空的條件時,它給出了0個結果,所以我目前正在嘗試最後的條件以查看這是爲什麼我的結果集是空的。錯誤是: 'assert:command failed:{「ok」:0,「errmsg」:「缺少$ cond」else「參數」,「code」:17082}:聚合失敗' – Syx

+1

您忘記了一些括號,是db.difficulty.aggregate([{$ match:...}]) – felix

+1

好極了,雖然這並沒有將所有結果合併到一個數據集中,但它仍然有我想要的記錄!非常感謝! – Syx