Currently exploring the MongoDB aggregation framework, let's consider a collection structured like this:
[
{
_id: ObjectId(123)
name: john,
sessionDuration: 29
},
{
_id: ObjectId(456)
name: moore,
sessionDuration: 45
},
{
_id: ObjectId(789)
name: cary,
sessionDuration: 25
},
]
The goal is to devise a query and pipeline that produces output in this format:
{
durationsArr: [29, 49, 25, '$sessionDuration_Field_From_Document' ];
}
This setup enables the calculation of the average duration across all documents. By aggregating the data into an array initiallly, the $avg
operation can be carried out effectively in the final stage.
Seeking advice on how to retrieve the array for the sessionDurationField
, or alternative optimal strategies for determining the average sessionDuration
from the collection. Appreciate a detailed explanation as I am relatively new to MongoDB aggregation.