Aggregating data with multiple arguments in MongoDB is a powerful

I'm attempting to retrieve multiple arguments from my MongoDB database. Currently, my code fetches the distinct values for dates and counts them. However, I am unsure how to include another argument to fetch a different set of distinct values and counts.

For instance:

Below is the output generated by my code:

[ { _id: '05-09-2019', count3: 1 },
  { _id: '06-09-2019', count3: 1 },
  { _id: '06-21-2019', count3: 1 },
  { _id: '06-30-2019', count3: 5 },]

My goal is to achieve the following result:

[ { _id: '05-09-2019', count: 1, branch: America, count2: 1},
  { _id: '06-09-2019', count: 1, branch: Germany, count2: 1},
  { _id: '06-21-2019', count: 1, branch: Philippines, count2: 1},
  { _id: '06-30-2019', count: 5, branch: Vietnam, count2: 1},]

Here is the snippet of code used to obtain distinct date values along with their counts:

router.get('/blooddonationarea', function(req, res) {
        Blooddonation.aggregate([{$group: {_id : "$date" , count :{$sum:1}}},{$sort: {_id: 1}}],function(err, date) {     
        res.json({ success: true, date: date });
        //console.log(date);
        });  

    });

I attempted to add this after the [] section but it did not return any values at all

[{ $match: { branch: { $eq: 'Rizal' } } },{$group: {_id : "$date", count2: {$sum:1}}},{$sort: {_id: 1}}]

Here is an example document:

_id:5c1f47dd59cdd931f4ce98ae
blood_product_donated:"Whole Blood"
branch:"Rizal"
deferral_type:"permanent"
date:"10-22-2019"

Answer №1

To achieve the desired outcome, one approach is to initially group the documents by both the date and branch keys. Subsequently, another pipeline step can be implemented where only the grouping is done based on the date key of the documents from the previous stage. Below is a sample code snippet illustrating this concept:

router.get('/blooddonationarea', (req, res) => {
    Blooddonation.aggregate([
        { '$group': {
            '_id': { 'date': '$date', 'branch': '$branch' },
            'count': { '$sum': 1 }
        } },
        { '$group': {
            '_id': '$_id.date',
            'count': { '$sum': '$count' },
            'branch': { '$first': '$_id.branch' },
            'count2': { '$first': '$count' } 
        } },
        { '$sort': { '_id': 1 } }
    ], (err, date) => {
        console.log(date);
        if (err) throw err
        res.json({ success: true, date });
    });
});

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

Implementing phone verification code delivery using ReactJS and Twilio client: Step-by-step guide

I've been scouring the internet for the past 8 hours and haven't been able to find a tutorial on using Twilio to send SMS messages with ReactJS. Does anyone know of a good tutorial for this? ...

Steps to display a comprehensive list of Node.js modules linked with npm

Is there a way to retrieve a list of global modules that have been linked with npm link, along with their respective local paths? Even better, can I get a comprehensive list of all globally installed modules, highlighting the ones that are linked using np ...

Tips for embedding svg within ion-content

My application is developed using Angularjs and ionic framework, incorporating cordova for hybrid mobile capabilities. However, when attempting to display svg content received from the backend, the expected diagram does not render properly. This is an exa ...

Tips for inserting and saving JSON data into an SQL server with Node.js

Attempting to execute a query in SQL Server using Windows authentication with Node.js. I have successfully implemented the GET request for select queries, but now I am facing issues with the POST request for insert queries. The problem arises when trying t ...

npm encountered an error with code EPEERINVALID, indicating an issue with

Welcome, I'm a new member here and encountering an npm ERR! code EPEERINVALID. Currently, my setup includes: nvm 0.32.1 npm 2.15.9 node v4.5.0 grunt-cli v1.2.0 grunt v0.4.5 While attempting to upgrade a package or module, I came across the foll ...

Troubleshooting: Responsive attribute settings causing ng-click in AngularJS slick carousel to malfunction

I am utilizing the angular wrapper https://github.com/vasyabigi/angular-slick to incorporate the slick slider into my project. Each individual slide within the slider has a ng-click function set up, which directs users to a different page upon clicking. I ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

The form is unable to detect invalid fields because of a nested view and inherited model structure

Currently in my project, I am utilizing Angular UI's ui-router for handling nested views. Specifically, within my layout on a distinct record page, the structure is as follows: Upon initial loading, everything functions smoothly - validation works, c ...

Node.js serves an Angular application without the need for additional JavaScript scripts

After developing an Angular application with a node.js server, I encountered an issue where the browser displayed the HTML code served by the server as text instead of rendering the web page correctly. This problem arose when I built the Angular project in ...

Error message encountered during NPM installation on Windows 10: Protocol not recognized or missing

Whenever I attempt to install packages using NPM on Windows 10, I encounter the following error message: Error: Invalid protocol : null Has anyone else experienced this issue before? https://i.stack.imgur.com/DdlmR.png ...

Setting up NodeJS modules

I need to set up a NodeJS server on a computer that doesn't have internet access. After copying and executing the .exe file, I realized I need to install some modules. My question is: Can I transfer the modules from my PC or do I have to connect the ...

Troubleshooting $templateCache not functioning correctly within the Angular.js angular-config

I keep encountering an error message that says "angular.min.js:6Uncaught Error: [$injector:modulerr]" whenever I try to implement $templateCache in my app.config block. Interestingly, when I remove the $templateCache parameter from app.config, the errors d ...

Highly Transferable Angular Modules for 'ng-cli'

I am managing a system with multiple Angular applications built using the ng-cli: FrontendLibs @company/ core/ src/ package.json index.ts main-app/ src/ package.json In this scenario, I have two Angular applications name ...

Asynchronous Return in NodeJS Class Methods

Currently, I am in the process of developing a JavaScript class that includes a login method. Here is an overview of my code: const EventEmitter = require('events'); const util = require('util'); const Settings = require('./config ...

Making a POST request using axios in a MERNStack application

After successfully using the express router to add articles with Postman, I encountered an issue when trying to send article information through Axios to MongoDB. Despite no errors appearing in the console, there was a message stating "SharedArrayBuffer ...

Sending an array of files to an express backend: A step-by-step guide

I am having an issue sending an array of images to my backend for upload using multer-s3. The process involves sending the images from a React frontend to a Node Express backend. Once submitted from the frontend, the images are formatted as follows: image ...

Retrieving a post based on the specified year, month, and slug

I'm in the process of developing a blog system using Node.js and Express. Each article is assigned a slug, which is stored in the database. For instance, hello-world. Right now, I can access a post by its slug only, like /article/hello-world. But, m ...

When using node.js express, the req.body object does not yield any results

My web server setup with express appears to be functioning correctly, however, I am encountering an issue where the req.body returns nothing. Despite not receiving any errors, the console.log(req.body) doesn't show anything in the console output. Stra ...

Leverage AJAX on the client-side for optimal performance while utilizing node.js

I am currently working on a simple nodejs application that displays HTML pages. Within this application, there are two buttons that are linked to JavaScript functions in separate files. One of the functions uses ajax, while the other does not. However, I a ...

The field "addWorkout" cannot be queried on the type "Mutation"

My journey with GraphQL has just begun, and after resolving a reference error in my previous question, I have encountered a new challenge. It appears that adding a workout is not working as expected, as the schema does not recognize it as a mutation field. ...