Kavishka Gamage
Kavishka Gamage

Reputation: 122

How to get an additional field in return document when using $group in MongoDB?

I want to find out the top performing sales representative in a company by orders they have submited.
So I grouped sales representative by name and total revenue in invoice model.
Invoice model represents the schema of invoice which is submitted by the sales representative.

analytics.controller.js

exports.topBestSalesrep = (req,res)=> {
    Invoice
        .aggregate(
            [
                {
                    $group : {
                        _id : '$salesrepName',                 
                        totalSum:{$sum:'$totalValue'}           
                    }
                },
                {
                    $sort:{totalSum:-1}
                },
                {
                     $limit : 10
                },
                // {
                //     $project:{ _id:1, area:'$customerArea' }
                // }
            ]
        )
        .then(data=>{
            return res.status(200).json(data);
        })
        .catch(err =>{
            return res.status(400).json(err);
        })

}

invoice.model.js

  salesrepName: {
    type: String
  },
  customerArea:{
    type:String,
    required:true
  },
  totalValue: {
    type: Number,
    required: true
  },
 

What I want ?

Here I want salesrepName and customerArea fields in the returned documents.

What I have tried ?

But even if I used $project I'm only getting salesrepName and totalSum fields in returned documents.

My Question

How can I get customerArea field in returned documents ?

Upvotes: 0

Views: 40

Answers (1)

Hari Lubovac
Hari Lubovac

Reputation: 622

typing from memory, so it might be wrong syntax, but lookup $push under $group.in mongo docs


                {
                    $group : {
                        _id : '$salesrepName',                 
                        totalSum:{$sum:'$totalValue'}  ,
                        items: { $push: $$ROOT }   // this emits the whole.object, becomes an array
                    }
                },

then you can project values that you need further in a subsequent stage

Upvotes: 1

Related Questions