Querying the sum in MongoDB returns empty results

Here is an example of a collection of activity rows:

{
  "_id" : ObjectId("5ec90b5258a37c002509b27d"), 
  "user_hash" : "asdsc4be9fe7xxx", 
  "type" : "Expense", 
  "name" : "Lorem", 
  "amount" : 10000, 
  "date_created" : 1590233938 
}

To find the total sum of the activities with this aggregate code:

db.activities.aggregate(
  [
    {
      $group: 
        {
          _id: "$id", 
          total: { $sum: "$amount" } 
        } 
    }, 
    { 
      $match: { type: "Expense", "user_hash": "asdsc4be9fe7xxx" } 
    } 
  ] 
)

The expected result should be: {_id: null, total: xxxxx }

What could be causing the actual result to differ? Any solutions for this issue? Thank you in advance.

Answer №1

There are two issues with your query:

  1. You are performing the sum aggregation on each individual document instead of doing it on the entire collection because you have specified _id: "$id", when you should be using _id: null.
  2. The match stage is being executed in the aggregating process after the group stage, but it needs to be done before. This is important because after grouping, the result will look something like this:
{
  "_id": null,
  "total": 15
}

This object does not contain any fields from the original documents, so no results will match. The sequence of stages is crucial as each stage operates based on the output of the previous one (with some exceptions where MongoDB optimizes the pipeline).

Therefore, the correct query should be:

db.activities.aggregate(
  [
    { 
      $match: { type: "Expense", "user_hash": "asdsc4be9fe7xxx" } 
    },
    {
      $group: 
        {
          _id: null, 
          total: { $sum: "$amount" } 
        } 
    },
  ] 
)

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

Simple Method to Retrieve JSON Data from a Data Attribute Using .attr() (or Similar Function)

It seems like I'm hitting a roadblock with something fairly basic, and I can't seem to find a solution. I've got a JSON array that I want to pass to my JavaScript using a data attribute on a div like this: <div id="scope" data-json=&apo ...

Perform a mongoDB query that filters out the data logged in the last 24 hours and groups it by ID along with a count

My current task involves filtering only the logs from the last 24 hours and grouping them by userId to determine how many times each user has logged in. Below is the schema of my MongoDB collection: Key Type timestamp(ISODate) Date ... ... tra ...

What is the procedure for generating a mouse event for clicking a tab in Selenium WebDriver?

As I work with Selenium WebDriver and Java, there is a tab named PR Per Product. Under the PR Reports tab, there are multiple tabs. In the PR tab, I used: WebElement menuHoverLink = driver.findElement(By.id("ext-pr")); actions.moveToElement(menuHoverLink) ...

Scrolling automatically to the first empty mandatory field with the help of AngularJS

After utilizing angular js to create a form with 7 input elements, I encountered an issue. Upon clicking submit, the form should scroll up to the first blank required field. However, it is not accurately identifying the left blank field. Any suggestions on ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...

Achieving a transparent inner box-shadow effect on hover: a step-by-step guide

Is there a way to make the black ring transparent upon hover by changing box-shadow: 0 0 0 5px #000, 0 0 0 10px green to box-shadow: 0 0 0 5px transparent, 0 0 0 10px green? It doesn't seem to be working for me. Any suggestions on how to achieve this ...

The Organization of Event Handling in ThreeJs

I am facing the challenge of managing multiple instantiated objects, each requiring its own handling of a specific event. Let's consider a class named "Foo": export default class Foo() { constructor(eventManager) { //reference to an event manage ...

The D3.js click event seems to be unresponsive

Currently, I am working with D3.js and backbone.js. My goal is to create a click event for each path element. Although I have provided an onclick event as shown below, the function does not seem to be triggered. createpath: function(nodes) { paths = ...

Tips for creating a div that slides from the right side to the left side

I received a code from someone and I need help with making the sliding div slide from right to left. Essentially, I want the div to hide on the right side and slowly move to the left within a width of 300px. Here is the HTML code: <a id="loginPanel"&g ...

The issue with Mongoose not fully storing the document

https://i.sstatic.net/zQ2L8.png Recently, I've been encountering an issue while attempting to store data in my MongoDB using Mongoose. Despite creating a data array, certain defaults like the company name fail to save successfully. Strangely, these v ...

Tips for designing a unique Facebook like button

I'm currently working on adding a Facebook like button to the product list page in my Prestashop website. So far, I've successfully added the Facebook like button using the code below. <div class="fb-like" data-href="{$product.link|escape:&ap ...

One effective way to transfer state to a child component using function-based React

My goal is to pass an uploaded file to a child component in React. Both the parent and child components are function-based and utilize TypeScript and Material-UI. In the Parent component: import React from 'react'; import Child from './ ...

The significance of namespaces in Vue.js event handling

Can namespaces be utilized with events, similar to how it's done in JQuery? For example, could one do the following: $.on('click.namespace') $.on('change.namespace') $.off('.namespace') // unregister both ...

objects bound to knockout binding effects

I have been struggling to understand why the binding is not working as expected for the ‘(not working binding on click)’ in the HTML section. I have a basic list of Players, and when I click on one of them, the bound name should change at the bottom of ...

Exploring the World of Repeating Elements in Print

As a newcomer to both Javascript and QA testing, I am eager to ensure that all elements are loaded in the repeater before proceeding with my selection. My current goal is straightforward - I want to confirm that the first and last elements are present in t ...

Easy ways to manipulate the style of array components in Vue.js

Hey there all you programmers, I'm reaching out to see if any of you have insight on how I can modify the style of a specific component within an Object array. This is the code snippet: <template> <div> <ul> <li v-fo ...

Failure to trigger custom event on FB pixel

I have installed the FB pixel helper browser plugin and I am confident that the FB pixel is properly implemented, as it is tracking pageviews correctly. However, I am facing an issue where the code for reporting a custom event is not working, even though ...

Learn how to retrieve and showcase MongoDB data in Node.js by incorporating URL parameters

Upon entering the URL with a specific parameter, I aim to retrieve and display data from Mongodb related to that parameter. For instance, if the URL is "http://www.example.com/product/1", information corresponding to id value "1" should be fetched and sho ...

What is the best method for extracting a property from an embedded document within an array in MongoDB?

Currently utilizing the native Nodejs driver with MongoDB 2.4 and seeking a solution to remove a property from documents embedded in an array. For example, how can I eliminate the gym property from documents within the grades array where the gym is 562e7c1 ...

Using the value of "1" for Schema.Types.ObjectId, a model was created in Mongoose

I'm currently working on the following task where my models are defined as: const channelSchema = new Schema({ name: {type: String}, country_id: {type: Schema.Types.ObjectId, ref: 'country'} }) and const countrySchema = new Schema ...