0

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.

1 Answer 1

1
  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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.