Reputation: 1871
I have a MongoDB collection "Marks" as shown below
_id Student_id Subject Mark
1 111 AAA 9
2 111 BBB 5
3 111 CCC 7
4 222 AAA 10
5 222 CCC 6
6 222 BBB 8
I need to find the average mark scored by student_id=111 in 3 subjects using MONGOOSEJS .I got a solution
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 is
[ { _id: 222, markAvg: 8 }, { _id: 111, markAvg: 7 } ]
I Want only {_id:111,markAvg:7}
when I pass student_id:111 as parameter.
Anyone please suggest an answer.
Upvotes: 0
Views: 558
Reputation: 311855
You need to add a $match
element to the top of your pipeline to filter the documents of the collection to just the ones you want as input to the $group
:
Mark.aggregate([
{ $match: { Student_id: 111 } },
{ $group: {
_id: '$Student_id',
markAvg: { $avg: '$Mark'}
}}
], function (err, results) {
if (err) {
console.error(err);
} else {
console.log(results);
}
});
Upvotes: 3