我有一個mongo集合,其中包含各自具有困難的問題。MongoDB限制條件
我想要做的是根據爲每個問題難度配置的金額查詢集合。所以說我有三個難度級別,1(easy,2(medium),3(hard),我已經配置了我的應用程序,以便在總共50個問題中抽取15個簡單,15箇中等和20個難度。
什麼是彙總這些數據的最佳方式是什麼?到目前爲止,我有沒有運氣與$match
或$cond
似乎並不能有條件限制$in
操作爲好。
我有一個mongo集合,其中包含各自具有困難的問題。MongoDB限制條件
我想要做的是根據爲每個問題難度配置的金額查詢集合。所以說我有三個難度級別,1(easy,2(medium),3(hard),我已經配置了我的應用程序,以便在總共50個問題中抽取15個簡單,15箇中等和20個難度。
什麼是彙總這些數據的最佳方式是什麼?到目前爲止,我有沒有運氣與$match
或$cond
似乎並不能有條件限制$in
操作爲好。
讓我們看看你有以下的文檔結構
{ "_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
和使用$cond
在project
到slice
陣列根據您的計數。請選擇以下查詢:
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()
請將您嘗試過的內容添加到帖子中,並添加樣本文檔以進行測試。 – Veeram
我試過的是不相關的,因爲你不能使用'$ match($ in ... $ limit)'作爲mongo,這正是我所希望的。用於測試的文檔可以是任意的,只需具有難度爲「關鍵字」的文檔並且值範圍從1-3,例如'{「difficuty」:Number(1)}',但我並不認爲這是相關的信息。 – Syx