Mohammad Farhan
Mohammad Farhan

Reputation: 129

MongoDB Aggregate - How to get array of fields

I am using MongoDB aggregation framework, suppose I am having collection structure like this:

[
  {
    _id: ObjectId(123)
    name: john,
    sessionDuration: 29
  },
  {
    _id: ObjectId(456)
    name: moore,
    sessionDuration: 45
  },
  {
    _id: ObjectId(789)
    name: cary,
    sessionDuration: 25
  },
]

I want to query and create a pipeline such that it returns something like this:

{
  durationsArr: [29, 49, 25, '$sessionDuration_Field_From_Document' ];
}

I am doing this because I want to get the average of durations from all the documents, so first add all of it into an array, then I will add the last stage where I do the $avg operation.

Any idea of how can I get the array of sessionDurationField? Or do you have any other best approach to calculate the sessionDuration average from the collection? Please thoroughly explain am new to MongoDB aggregation.

Upvotes: 0

Views: 28

Answers (1)

Yong Shun
Yong Shun

Reputation: 51195

  1. $group - Group all documents.

    1.1. $avg - Calculate the average of sessionDuration for all documents.

db.collection.aggregate([
  {
    $group: {
      _id: null,
      avgSessionDuration: {
        $avg: "$sessionDuration"
      }
    }
  }
])

Demo @ Mongo Playground

Upvotes: 1

Related Questions