David Faizulaev
David Faizulaev

Reputation: 5721

Mongoose aggregate column as average and output with additional fields

I would like to query the database get a grouped result which will calculate an average result and in addition, output additional fields from the object.

I have a schema which like this:

    resturantName: {type:String},
    resturantLocation: {type:String},    
    comfort: {type: Number, min: min, max: max, default: 0},
    cleanliness: {type: Number, min: min, max: max, default: 0},
    valueForMoney: {type: Number, min: min, max: max, default: 0},
    avgRating: {type: Number}

I query the database according to 'resturantLocation' and would like to calculate the 'total_average_rating', in addition output the restaurant name & location.

I've tried multiple queries but I keep getting various errors, here is my latest attempt:

query = [
    { "$match": { "resturantName": resturantName} },
    {
        "$group": {
            "_id": 1,
            "resturantName": resturantName,
            "resturantLocation": "resturantLocation",
            "total_average_rating": { "$avg": "$avgRating" }
        }
    }   
];

I looked into using $project, but I doubt it fits my needs.

Please advise.

Upvotes: 0

Views: 37

Answers (1)

s7vr
s7vr

Reputation: 75924

You can try below query.

$first to keep the additional fields & $avg to get the average rating.

query = [
  { "$match": { "resturantName": resturantName} },
  { "$group": { 
       "_id": "$resturantName", 
       "resturantLocation": {"$first":"$resturantLocation"}, 
       "total_average_rating": { "$avg": "$avgRating" 
        } 
     } 
  }
];

Upvotes: 1

Related Questions