Home:ALL Converter>how to aggregate if there are two conditions to be met in mongodb

how to aggregate if there are two conditions to be met in mongodb

Ask Time:2014-02-02T02:34:28         Author:Monece Solis

Json Formatter

Hi im new to mongodb and I am confused in aggregating when there are two conditions to be met

The two conditions are: The lowest score and the type should be homework

This is my schema design:

    "_id" : 0,
"name" : "aimee Zank",
    "scores" : [
        {
            "type" : "exam",
            "score" : 1.463179736705023
        },
        {
            "type" : "quiz",
            "score" : 11.78273309957772
        },
        {
            "type" : "homework",
            "score" : 6.676176060654615
        },
        {
            "type" : "homework",
            "score" : 35.8740349954354
        }
    ]
}

What I plan to do is to query the lowest homework score. So in my schema design above I plan to query the third element because it is the lowest score of the homework.

My mongodb query I have made right now is this:

db.students.aggregate( [ 
    { "$unwind": "$scores" },
    { "$match" : {"type" : "homework"}},
    {"$group": { '_id':'$_id', 'score': {'$min': "$scores.score" } } }
    ])

but all I get after doing this query is:

{ "result" : [ ], "ok" : 1 }

Author:Monece Solis,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21501916/how-to-aggregate-if-there-are-two-conditions-to-be-met-in-mongodb
ahrzg :

You might look at your condition in \"match\": you have to specify the full path.\n\nThat means you should do like this: \n\n\n[{\"$unwind\": \"$scores\"}, \n{\"$match\": {\"scores.type\":\"homework\"}}, \n{\"$group\": { '_id':'$_id', 'score': {'$min': \"$scores.score\" } }}]\n\nnotice \"scores.type\"",
2014-02-01T18:45:19
yy