Reputation: 313
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
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