0

I have following records in mongodatabase.

> db.student.find()
{ "_id" : ObjectId("52ca76140e468ba197e50c23"), "name" : "pratik", "subject" : "maths", "marks" : 68 }
{ "_id" : ObjectId("52ca762b0e468ba197e50c24"), "name" : "pratik", "subject" : "biology", "marks" : 96 }
{ "_id" : ObjectId("52ca77a90e468ba197e50c25"), "name" : "pratik", "subject" : "maths", "marks" : 40 }

From this record I want to know the total marks obtained for just maths subject. Here is what I have tried,but I don't know what is going wrong in the following query.

db.student.aggregate(
{$match: { 'subject': "maths"}},
{ $group : { _id :{ name:"$name",subject:"$subject",marks:"$marks" },
            total: { $sum : "$marks"}}
})

{
        "result" : [
                {
                        "_id" : {
                                "name" : "pratik",
                                "subject" : "maths",
                                "marks" : 40
                        },
                        "total" : 40
                },
                {
                        "_id" : {
                                "name" : "pratik",
                                "subject" : "maths",
                                "marks" : 68
                        },
                        "total" : 68
                }
        ],
        "ok" : 1
}

Could you please let me know what has went wrong in the above query along with the correct answers. Also suggest me the appropriate guide to use the aggregation module so that I can use it efficiently.I am beginner to aggregation module of mongo database.

Thanks in Advance.

1 Answer 1

1

The problem is the marks field in the group within the _id. It will group upon mark scores then which is useless to you, instead you want:

db.student.aggregate(
    {$match: { 'subject': "maths"}}, 
    {$group : { 
        _id :{ name:"$name", subject:"$subject" }, 
        total: { $sum : "$marks"} 
    }}
);
Sign up to request clarification or add additional context in comments.

2 Comments

This has worked for me. Thanks Sammaye.Could you please suggest me the appropriate guide to use the aggregation module so that I can use it efficiently.I am beginner to aggregation module of mongo database and bit confused.
@user1961408 A good one is normally the zip code example: docs.mongodb.org/manual/tutorial/aggregation-zip-code-data-set it should teach you most things

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.