Hariwarshan
Hariwarshan

Reputation: 313

How to dynamically set the field in Mongoose when doing aggregation?

someModel.aggregate([{
                        $group: {_id:null,
                         average:{$avg:"$low"}}
                    }
                    ])

in the above code "low" is a field where i want to perform average.but am having some more fields too. when i get the value of field i cant dynamically set it. i need to use if/else like below to achieve this.

if(field==="low"){
      someModel.aggregate([{
                            $group: {_id:null,
                             average:{$avg:"$low"}}}])
}else if(field==="high"){
     someModel.aggregate([{
                            $group: {_id:null,
                             average:{$avg:"$high"}}}])
}

is this the only way to do so?

Upvotes: 1

Views: 32

Answers (1)

mickl
mickl

Reputation: 49985

Try to concatenate that using field variable:

let field = 'low';
let group = {  $group: {_id:null,
                             average:{$avg:"$" + field}}};

console.log(group);

someModel.aggregate([group]);

Upvotes: 2

Related Questions