Taking sum/average of columns in mongoosejs

javascript, mongodb, mongoose, node.js

Solution

If you're using MongoDB 2.2 you can use the aggregation framework for this:

var Mark = mongoose.model('mark', new Schema({
    Student_id: Number,
    Subject: String,
    Mark: Number
}));

Mark.aggregate([
        { $group: {
            _id: '$Student_id',
            markAvg: { $avg: '$Mark'}
        }}
    ], function (err, results) {
        if (err) {
            console.error(err);
        } else {
            console.log(results);
        }
    }
);

Output:

[ { _id: 222, markAvg: 8 }, { _id: 111, markAvg: 7 } ]

Problem

I have a MongoDB collection "Marks" with fields student_id,Subject,Mark. I want to the average value of marks scored by a particular student. My project is in NodeJs and I am using MongooseJS for object modeling. How to query the this using MOngooseJS? EXAMPLE ``` Student_id Subject Mark 111 AAA 9 111 BBB 5 111 CCC 7 222 AAA 10 222 CCC 6 222 BBB 8 ``` I want average of marks scored by student(id) 111 i.e((9+5+7)/3)=7)

Original source