Add up unique values in MongoDB

Document layout

    {
        "_id": "5a21c5dff772de0555480ef5",
        "date": "2017-10-06T00:00:00.000Z",
        "amount": 1,
        "location": "Canada",
        "__v": 0
    }

I am looking to calculate the total amount for each location and present the output in the following format:

{
  "location": "Canada",
  "amount": 8
}

Could you provide some guidance on how to construct an aggregate query for this purpose (or suggest an alternative approach)?

Answer №1

If you're looking to group and summarize data in MongoDB, the aggregation framework is your friend.

You can achieve this by using the $group stage along with the $sum operator to aggregate documents based on location:

db.collection.aggregate([{$group:{_id:"$location", totalAmount: {$sum: "$amount"}}])

If you need the resulting field to be named 'location', add a $project stage to rename '_id' to 'location':

db.collection.aggregate([
     {$group:{_id:"$location", totalAmount: {$sum: "$amount"}}},
     {$project: {location: "$_id", totalAmount: 1, _id:0}}
])

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

Changing the action of a form dynamically with Javascript and Selenium in a Java environment

I am having trouble updating the action attribute of a form using JavaScript and Selenium in Java. Here is the snippet of HTML from the site: </div> <div class="contionue-shopping-wrapper"> <form class="co-formcontinueshopping" action="htt ...

Updating the data when session begins

I am having an issue with two PHP files (index.php & data.php). The first file sends data to the second file, which runs every second to display the data. However, the problem is that the data is not updating. Perhaps looking at the code will provide a be ...

Learn the art of closing an AngularJS accordion automatically when another accordion is opened within an AngularJS application

I have encountered an issue with the AngularJS accordion functionality. It seems that when I have multiple accordions, such as accordion-1, accordion-2, and accordion-3, they all open simultaneously if clicked on individually. My main concern is: How can ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Alter the font color upon clicking the menu using jQuery

When I click on the menu and sub-menu items, I want to change their colors along with their parent. You can see an example of how I want it to work here. However, currently, when I click on a sub-menu item, the color of the parent menu item gets removed. ...

Listing entries in NodeJS after a certain date with MongoDB

I successfully created an API call to mongoDB that retrieves all entries, functioning without any issues. Here is the code snippet: MongoClient.connect(url, function(err, db) { if (err) return res.json("Error:Database Connection error&q ...

Separating Angular JS controller and Factory into individual files allows for easier organization and

As someone new to web development and Angular, I recently created a module, factory, and controller all in the same file (app.js). Below is an example of the code: //Main Module var ipCharts = angular.module('ipCharts', []); //Factory ipCharts. ...

Return an unspecified value when using Array.map function

How can I prevent this map from returning undefined? var onCompareSelectedClick = function () { var talentProfileInfoForAppliedResources = appliedResourcesEntries.map(function(res) { console.log(res); if(res.c ...

Is there a way to directly display all the content in pagination format without a print preview option?

I have been tasked with implementing a feature that involves displaying content using pagination and allowing users to print all the content at once with a single click on a print button. However, I am currently experiencing an issue where clicking the pri ...

Storing user input with AngularJS

I have a form below that I am trying to save. Please review my HTML code for the form. HTML <form ng-submit="save()"> <input type="text" ng-model="user.name"/> <input type="text" ng-model="user.age"/> <input type="text" n ...

What steps can be taken to ensure the random generator continues to function multiple times?

My little generator can choose a random item from an array and show it as text in a div. However, it seems to only work once. I'm looking for a way to make it refresh the text every time you click on it. var items = Array(523,3452,334,31,5346); var r ...

Guide on transforming UTC time from the server to the local time of users during a GET request

I am currently facing a challenge where I need to verify if the date of the last time an element was clicked matches the current date. Due to my server generating the current date which is 5 hours ahead of my local time, there is a discrepancy causing the ...

Reset the child JSP page to its original appearance

Displayed below is a JSP page: <div id="tabs-7" style="width: 100%;"> <form:form id="deviceForm" name="" modelAttribute="" enctype="multipart/form-data"> <div class="inputWidgetContainer"> <div class="inputWidget"> <table> ...

To successfully process this file type in JavaScript, you might require a suitable loader

Currently, I am facing an issue with my MVC application while trying to integrate Bootstrap 5 using Webpack. Despite attempting various workarounds with stage-0, stage-2, and stage-3, none have proven successful for me. I suspect that the problem lies wit ...

When defining multiple types for props in Vue, the default behavior for Boolean type props is not preserved

Imagine you have a component called MyComponent with a prop named myProp declared as: props: { myProp: Boolean } By simply using <MyComponent myProp/>, the default behavior would set myProp to true. However, this simplicity is lost when there ...

The ng-model is being set to the default value, however the select element fails to display the text and instead appears blank

Having trouble displaying a default option in a select tag after retrieving a list of options from the server. The model is being set correctly, but the select shows up blank, and I can't figure out why! I've attempted various solutions from Sta ...

Ways to add a delay between test cases in Protractor

Currently, I am experimenting with the protractor tool in combination with cucumber and noticed that the tests are running extremely fast. To verify whether elements are being clicked or not, I attempted to use the sleep() method without success. Additiona ...

Executing a conditional onClick function when the page loads

I have implemented a php-based authorization system that loads different authorization levels into a JavaScript variable. My goal is to disable certain onclick events based on the user's authorization level. I've come up with the following code ...

Arrange JSON information in an HTML table with distinct header rows for every data category

I have a JSON object with a key:value pair named callRoot. Some examples of values for this pair are @S, @C, and @W. There are multiple objects that share the same value and I want to create an HTML table head row at the beginning of each group and repeat ...

I'm curious why my express route functions properly when I write it first, but throws a cast error if I place it elsewhere in

One of the routes in my app involves a friend route that I have registered on the user route. The user route is also registered in the app. In the user schema, I have utilized mongoose.Types.ObjectId. Mongoose Version: 5.9.19 Within User.js: router.use ...