I’m very new to MongoDB and am trying to figure out how to calculate the average of certain fields through the the node-js
driver.
Here is a minimal toy example to demonstrate my data. This is one record out of many:
[
{
"_id": 123,
"createdAt": "2021-12-25",
"data": {
"dem_num_age": {"value": 25},
"dem_num_height": {"value": 100},
"dem_num_weight": {"value": 160},
"dem_num_n_of_kids": {"value": 0},
"dem_cat_fam_status": {"value": "married"},
"preferred_pet": {"value": "dog"},
"preferred_color": {"value": "purple"},
"preferred_movie": {"value": "titanic"}
}
},
{...} // another record
]
And I want to query the DB to get the average (across records) of each field inside data{}
that starts with dem_num
. Thus, the desired output of the query should be a javascript
object with those averages:
{
"dem_num_age": 35.2,
"dem_num_height": 123.7,
"dem_num_weight": 188.5,
"dem_num_n_of_kids": 1.5
}
Any idea how I could do that in node-js
?
Many thanks!