MongoDB按条件限制

时间:2016-12-05 17:33:53

标签: mongodb mongoose

我有一个mongo集合,其中包含各自有困难的问题。

我想要做的是根据为每个问题难度配置的数量来查询集合。

所以说我有三个难度级别,1个(简单,2个(中等),3个(硬)我已经配置我的应用程序拉15个简单,15个中等,20个难度,总共50个问题。

汇总这些数据的最佳方法是什么?到目前为止,我对$match$cond没有好运,似乎也没有条件限制$in运算符。

1 个答案:

答案 0 :(得分: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上创建群组,并根据您的计数在$condproject数组中使用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()