Before we started
- Kindly scan through the default get all query response body from [response.json]
- Checkout [Tour Schema] for the schema type object
- In this tutorial, we will trying to create some new fields by grouping and according based on their value in difficulty which will only contains
easy
,medium
anddifficult
Note: This controller function will be under a route call ‘/api/v1/tours/tour-stats’.
Code
|
|
Result
{
"status": "success",
"data": {
"stats": [
{
"_id": "difficult",
"num": 2,
"numRatings": 41,
"avgRating": 4.6,
"avePrice": 1997,
"minPrice": 997,
"maxPrice": 2997
},
{
"_id": "medium",
"num": 3,
"numRatings": 70,
"avgRating": 4.8,
"avePrice": 1663.6666666666667,
"minPrice": 497,
"maxPrice": 2997
},
{
"_id": "easy",
"num": 8,
"numRatings": 159,
"avgRating": 4.5875,
"avePrice": 661,
"minPrice": 50,
"maxPrice": 1997
}
]
}
}
Explanation
- Aggregation Pipeline provides tons of operators just to achieve your desire goal. Check out [https://docs.mongodb.com/manual/reference/operator/aggregation/] for more built-in operators
- First of all, we can use the operator
$match
to filter out the value according to the field we set. This case we only want to get theratingsAverage
is$gte
greater or equal than 4.5 - Next, we can create our own response field by grouping the existing field in the Database from specifying the field name inside
_id
.- The new field name will follow in this standard
newFieldName : { operator : '$<FieldName> }
- For example, We can use the operator
$sum
to count the total number ofeasy
in difficulty fieldnum: { $sum: 1 }
. - When aggregation pipeline is running, it will then loop through the response and add the value assigned to the $sum operator. This case will be 1
- The new field name will follow in this standard
- We also uses the operator like
$avg
to get the Avarage number,$min
to get the minimum value and$max
to get the maximum value - We can the the operator
$sort
to sort the field we want. This case we already create our custom field (after$group
operator), so it’s applicable to put inside the$sort
operator as well. The concept is same as previously we did for Mongo.find query whereby 1 is sort ascending and -1 is sort descending