pranshu verma
pranshu verma

Reputation: 151

How can I find Average of a document item in a collection in mongoose?

   const scoreSchema = new mongoose.Schema({
    rollno:{
        type:Number,
        unique: true
    },
    first_round:{
        type:Number,
        validate(value){
            if(value > 10){
                throw new Error('Maximum marks is 10')
            }
        }
    },
    second_round:{
        type:Number,
        validate(value){
            if(value > 10){
                throw new Error('Maximum marks is 10')
            }
        }
    },
    third_round:{
        type:Number,
        validate(value){
            if(value > 10){
                throw new Error('Maximum marks is 10')
            }
        }
    },
    total:{
        type:Number,
        }
});

I need to find averages of first_round, second_round etc for all the records combined. How can I do that? I cannot figure out how we can find averages in mongoose. Any help would be appreciated.

Upvotes: 1

Views: 1079

Answers (2)

turivishal
turivishal

Reputation: 36104

If you want average of all the records combined then try aggregate(),

  • $group by null and average all fields using $avg
let result = await ModelName.aggregate([
  // match condition to match for specific rollno
  // { $match: { rollno: { $in: [1,2] } } },
  {
    $group: {
      _id: null,
      total_average: { $avg: "$total" },
      first_round: { $avg: "$first_round" },
      second_round: { $avg: "$second_round" },
      third_round: { $avg: "$third_round" }
    }
  }
], { allowDiskUse: true });
console.log(result);

Playground

Upvotes: 1

Fahad Subzwari
Fahad Subzwari

Reputation: 2325

You can acheive this using mongoDB aggregation. And in aggregation you can use $group to evaluate your avgs of each rounds for all records.

db.sales.aggregate(
 [
  { 
   $group:
     {
       _id: "$item",
       first_round_av: { $avg: "$first_round" },
       second_round_av: { $avg: "$second_round" },
       third_round_av: { $avg: "$third_round" },
     }
   }
  ]
 )

Upvotes: 0

Related Questions