Home > OS >  Mongoose sum fields with the same values
Mongoose sum fields with the same values

Time:07-19

I have mongoose schema like so:

const RecordSchema = new mongoose.Schema({
    day: Number,
    week: Number,
    month: String,
    year: Number,
    state: String,
    station: String,
    revenue: Number,
    sales: Number,
    date: {
        type: Date,
        default: Date.now()
    }
})

I'm trying to write a query where I can get all the states, then sum up the revenue of all the states that have the same name. Something like this:

{...state: LH, revenue: 1200}
{...state: PH, revenue: 300}
{...state: LH, revenue: 300}
{...state: PH, revenue: 250}

I want to get all these records in one query like so:

[{state: PH, revenue: 550}, {state: LH, revenue: 1450}]

CodePudding user response:

You just have to use plain $group with accumulator

 db.collection.aggregate({ //Single pipeline, hence no array notation
   $group:{
     _id: "$state", //Index on state field will improve performance
     revenue: {$sum: $revenue} //accumulator
   }
 })
  • Related