MongoDB: total value of combined fields

Our records show:

{a: 1}
{a: 5}
{a: 3}

Is there a way to aggregate this data and calculate the current sum?

{a: 1, cs: 1}
{a: 5, cs: 6}
{a: 3, cs: 9}

Answer №1

If you're looking to achieve this specific functionality in MongoDB, your best bet currently is using mapReduce. This method allows for the storage of a "global" variable, crucial for maintaining a "running total" as seen in the example below:

db.collection.mapReduce(
    function(){ 
        totals += this.a;
        emit(this._id, {"a": this.a, "cs": totals});
    },
    function() {},  // no reduction needed
    {
        "out": { "inline": 1 },
        "scope": { "totals": 0 }
    }
);

While there may not be explicit grouping involved here, it's definitely possible if required. The focus here is on preserving a "running total" for each individual record.

The "mapReduce" command utilizes the "scope" attribute in this case to facilitate the use of a global variable essential for this process.

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

Is there a way for me to determine which .js script is modifying a particular HTML element?

Let's take a look at a specific website as an example: This particular website calculates value using a .js script embedded in the HTML itself. Upon inspecting the source code by pressing F12, we can locate the element containing the calculated valu ...

Preventing AngularJS from Binding in Rows: A Solution

Currently, I am utilizing AngularJS version 1.5.3 and I am facing an issue with my services. I have two services - one that retrieves Area names and the other that fetches details for each Area. In my code, I first call the service to get the Area names an ...

Error message when trying to access a property that is not defined in objects returned

I am currently utilizing DWR for AJAX implementation. The method created by the creator is public ArrayList<CompanyRecord> step4QueryTable() throws JCoException {...} The structure of CompanyRecord class is as follows: public class Company ...

Guide to concealing a language path within a url using an exception

I currently have a website with various language versions, with English set as the default. Is there a way to conceal the /en/ path from the URL? (making an exception for just en) I want to maintain the other languages unchanged. www.website.com/en/ (wa ...

What is the best way to retrieve duplicate input values using JavaScript?

Hey there! I have created a button that, when clicked, will add two input fields one after the other. I achieved this using the clone() function. However, my issue arises when I input values into each field and then click the submit button, as I only recei ...

The Mysteries of MySQL and Node.JS Post Requests

As a beginner in networking, I have successfully used this code with a REST API like Postman to achieve my desired outcome: router.post('/', function(req,res,next){ var reqObj = req.body; console.log(reqObj); req.getConnection(fu ...

Guide on how to automatically log out a user at a designated time

I am working on a basic application with login functionality using webforms, and I want to automatically log out the user at a specific time for updates. For example, at 13:30, I need to logout the user from the website and redirect them to the login page. ...

HTTP AJAX request automatically switching to HTTPS

Currently, I am facing an issue with making an AJAX POST request from a Chrome extension to my AWS app. The request is defined over http instead of https. I have made sure to incorporate the necessary CORS headers in my AWS app as seen below: app.use(func ...

issue with CSS transition delay not functioning properly in display

Check out this quick demo that I put together: https://codepen.io/marekKnows_com/pen/LaRPZv My goal is to have the red box only show up 2 seconds after the mouse hovers over the blue box, and disappear immediately when the mouse leaves. This is the HTML ...

Unable to change background-image as intended

Here is an example of my HTML code with an initial background image: <div id="ffff" style="width: 200px; height: 200px; background-image: url('/uploads/backroundDefault.jpg')">sddsadsdsa<br>dffdsdfs</div> Everything seems to b ...

The functionality of d3.dispatch() is not performing as anticipated

Recently, I delved into the world of D3.js to explore its capabilities. One particular concept that caught my attention is d3.dispatch(), and I've been experimenting with it for about a week now. Below is a simple example: <script src="d3.min. ...

Is there a way to showcase the content of a text file in a sequential manner using Javascript/AJAX?

I am attempting to retrieve text data from a server file and exhibit it within a specific division on my website. Check out the AJAX/Javascript code I have been working with: <body onload="loadXMLDoc()"> <script> function loadX ...

How can I troubleshoot the 'mdDialog console error' that says 'cannot read property element of null'?

Two of my templates are named Left_template_view_html and center_template_view_html When I click on a md-button in the Left_template_view_html I am attempting to display an mdDialog on the document.body What should I pass into the parent parameter: angu ...

Encountering the error message "handleChange is not a function" when trying to select a date in Material UI

Encountering an error message 'handleChange is not a function' when selecting a specific date in the DatePicker component. The DatePicker component is nested within the Controller component of react-hook-form. The expected behavior is to display ...

Is it possible to retrieve the complete file path in a form?

My goal is to retrieve a file using an input element of type "file". This element is located within a partial view, and I need to send it to the controller or request it there using "Request.Form["inputFile"];". However, this method only provides me with t ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

Guide to customizing Highcharts for extracting targeted JSON information

I've been dedicating a significant amount of time trying to unravel this puzzle. Typically, I prefer researching solutions rather than posing questions, but this challenge has me completely perplexed. My goal is to generate a Highchart using data from ...

Unable to append attributes to an object - Issue with Node.js/Mongoose

I have been attempting to verify if a user account exists in either the User model or TempUser model. Unfortunately, I am facing a challenge where I am unable to include a discovered value in an object for further processing during the conditional check. ...

What are effective strategies for safeguarding my AngularJS application code, particularly from unauthorized access through the browser's source code?

I am currently working on an AngularJS application. I have encountered a challenge where the end user is able to view the app code from the browser's source code. I am seeking advice on how to address this issue effectively. Is there any recommended ...

Upgrade to the latest Gulp version and transition away from using the gulp.start function

Currently in the process of updating all my gulp v3 projects to v4, but running into an issue with the gulp start function. Upon executing gulp start in gulp v4, I encounter an error. This was the code snippet I used in v3: gulp.parallel within gulp.seri ...