Acquiring an array of fields using MongoDB Aggregate

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.

Answer №1

  1. $group - Grouping all the documents together.

    1.1. $avg - Computing the average of sessionDuration across all documents.

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

See a live demonstration on Mongo Playground

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to conceal an element solely in live production environments?

Is there a way in my Angular code to specifically target the PROD environment? <div *ngIf="environment !== 'prod'" class="col-6"> <button class="btn btn-primary text-white add-photo" (cli ...

Struggling to retrieve data from AJAX POST request [Revised Post]

I am encountering an issue with posting a form using the AJAX POST method in jQuery. I am using the serialize method to retrieve the form data, but it seems to fail. The problem might be related to the JavaScript files of the Steps Wizard plugin that I am ...

Identify when a click occurs outside of a text input

Whenever text is typed into the textarea, the window changes color. The goal is to have the color revert back when clicking outside the textarea. <textarea class="chat-input" id="textarea" rows="2" cols="50" ...

How to automatically set the radio button as "checked" with Javascript upon loading the page

With the dark mode switch javascript from Bootstrap 5 (https://getbootstrap.com/docs/5.3/customize/color-modes/#javascript), I am attempting to ensure that a radio button is set to "checked" when the page loads, as well as when the color mode is changed. ...

Removing data from database with ajax

I am encountering an issue with deleting records from my database using ajax and jquery. When I click the button, nothing happens. Here is the relevant css code: <button class='delete_p' id_p='<?php echo $post_id; ?>'>x< ...

Functionality of multiple sliders

Is there a more efficient way to handle the fading in and out of sections on a slider? I currently have separate functions for each section, but I'd like to simplify it so that I only need one function for all 100 sections. Any suggestions? $(&apos ...

Retrieve a dynamic value from an object

Is it possible to dynamically pass a context from the server to the client so that the client can retrieve a value from an object more efficiently? For example, the server sends an object with a key-value pair like this: "booking__validating_carrier_ ...

Is there a way to view the contents of a file uploaded from <input type="file" /> without the need to send it to a server?

Having trouble uploading a JSON file from my local disk to Chrome storage. Whenever I use the <input type="file"> tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...' ImportExport Component: ...

JavaScript - Getting the name of a sub-class when extending the Error class

In my application, I have custom Errors that I wanted to check for later using the constructor name. However, when I extend Error in my classes, the constructor name always displays as "Error" instead of the actual name I assigned to it. I conducted some ...

How to update a single field in a MongoDB document using Java without affecting the entire document

Currently, with MongoDB 3.2 and the MongoDB Java Driver 3.2, I am utilizing a code snippet to update documents in my database: unfetchedEpisodes.stream() .forEach(ep -> { BasicDBObject updatedFields = new BasicDBObject(); updatedFiel ...

Issue with Accordion Panel Content Scroll Bar

Hello there, I've encountered a puzzling problem with my website. My objective is to insert a Time.ly Calendar widget into one panel of my accordion. On this page, "TOURNAMENTS: , the widget appears exactly as desired. However, when I replicate the c ...

Generate a dynamic add to cart section for every last configurable choice, assisting with this task

Currently, I am involved in a project that involves displaying configurable options on a product page, along with querying the database to check which vendors carry the product. The list of vendors is then displayed using JavaScript. In order to make the ...

What is the reason behind the cautionary note associated with Vue's provide and inject functionality?

Considering incorporating Vue's new provide/inject feature into a project, I came across a warning in the official Vue documentation: The documentation states that provide and inject are primarily intended for advanced plugin/component library usage ...

Unsuccessful execution of JavaScript in returned HTML after being appended with jQuery .load() or .ajax()

I have attempted to use .load() and $.ajax in order to retrieve some HTML that needs to be added to a specific container. However, the JavaScript enclosed within the fetched HTML is not executing when I add it to an element. When employing .load(): $(&ap ...

What is the process for initiating an application dynamically using second.html in Vue3?

I'm currently working on a Vue3 project. In the main.js file: import { createApp } from "vue"; import App from "./App.vue"; const app = createApp(App); import store from "./store"; app.use(store); import router from &quo ...

Is there a way to activate a click event when I click on a button that is located outside of the dialog element?

In my Vue 3 app, I am using the native HTML dialog element as a modal. I have managed to position a button outside of the modal with absolute positioning. However, I am facing an issue where I cannot trigger a click event (displayNextModal) when clicking ...

Is there an Angular directive that can replicate a mouseenter event?

Is there a way to simulate a mouseenter event with a directive? I have been searching for a directive that can simulate a mouseenter event, but all I have found so far is one that binds a function to mouse over or karma tests for simulating mouse over. W ...

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

accessing a group of objects within an array using ajax

After receiving three data sets from an ajax call, I combine them into an array using this method: return json_encode([$salesOrder, $soAddressDetails, $lineItems]); When I check the returned data in the view, I observe something similar to the following ...

A guide on sorting MongoDB arrays in JavaScript to arrange them in descending order based on two specific fields

I am attempting to organize MongoDB arrays in a descending order. I have devised some JavaScript code to transform all the documents into JSON arrays, but I also need to arrange them in a descending order. Here is the code I have written: const result = xp ...