Summing up values based on specific conditions in Mongoose: `$sum

I am currently working on a query that involves using find and aggregate to retrieve data from the Schedule model. I need to calculate the total sum of services and the total value of services, but with a condition where the status is equal to 2. Is it possible to achieve this?

Here is my current query:

 Schedule.find(findTerm)
    .skip(req.body.page * req.body.limit)
    .limit(Number(req.body.limit))
    .select(
      "service.name value scheduleStart scheduleEnd comissionValue status paymentMethod"
    )
    .exec((err, response) => {
      if (err) res.status(500).send(err);

      Schedule.find(findTerm)
        .count()
        .exec((error, count) => {
          if (error)
            res.status(500).send({
              error,
              code: 0,
              message: "Error."
            });

          Schedule.aggregate([{
              $match: {              
                store: req.body.store,             
              }
            },
            {
              $group: {
                _id: {
                  id: "$store"
                },
                totalValue: {
                  $sum: "$value"
                },
                totalServices: {
                  $sum:  {
                    $cond: [ {
                      $eq: [ "$status", 2 ]
                    }]
                  }
                },
                count: {
                  $sum: 1
                }
              }
            }...

Result of my query:

...{
            "service": {
                "name": "CABELO + BARBA"
            },
            "comissionValue": 0,
            "paymentMethod": 0,
            "_id": "5bfec336c6f00d2e88f8d765",
            "scheduleStart": "2018-11-28 14:35",
            "scheduleEnd": "2018-11-28 15:45",
            "status": 2,
            "value": 75
        },
        {
            "service": {
                "name": "Barba"
            },
            "comissionValue": 0,
            "paymentMethod": 0,
            "_id": "5bfec3ffc6f00d2e88f8d766",
            "scheduleStart": "2018-11-28 18:30",
            "scheduleEnd": "2018-11-28 18:50",
            "status": 2,
            "value": 20
        }
    ],
    "count": 4299,
    "group": [
        {
            "_id": {
                "id": "5b16cceb56a44e2f6cd0324b"
            },
            "totalValue": 777780048281, //correct value
            "totalServices": 945, //incorrect value
            "count": 676
        }
    ]
}

I need to only include objects in the totalServices sum where the status is equal to 2 (I attempted to use $cond but it did not work).

Answer №1

If you want to sum the value field based on a condition, use the $cond operator. Specifically, if the value of the status field is equal ($eq) to 2, then include the value in the summation; otherwise, pass 0.

Schedule.aggregate([
  { "$match": { "store": req.body.store }},
  { "$group": {
    "_id": { "id": "$store" },
    "totalValue": { "$sum": "$value" },
    "totalServices": {
      "$sum": { "$cond": [{ "$eq": ["$status", 2] }, 1, 0] }
    },
    "count": { "$sum": 1 }
  }}
])

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

Background of jQuery-UI Slider

Can the background color of a jQuery-UI Slider widget be set using JavaScript? This is the default setting: What I am trying to accomplish is the following: The green range should be determined based on historical data. I want to visually show the user ...

What is the most effective method for live-updating a field every 5 seconds in Laravel?

I want to monitor the database to see if a new row is created for each user and display a popup message to notify them. I'm debating between using pusher/socket or making an Ajax call every 5 seconds to achieve this live update without page refresh. I ...

Limiting the number of results returned when using the Request module in Node.js for MongoDB

Currently, I am facing an issue with setting a query limit for my mongodb queries using the request module. Despite trying different methods to limit the number of results displayed, as suggested in the mongodb documentation: https://mongodb.github.io/node ...

What is the mechanism behind the workings of the requestAnimationFrame loop?

I'm currently studying the ins and outs of javascript and Three.js but I'm struggling to grasp the concept of how the requestAnimationFrame function operates. Could someone please break down the following code in simple terms for me? ( feel free ...

Is it possible to dynamically insert a ng-mouseover in AngularJS using Javascript?

It seems like there is an issue with this code: var run_div = document.createElement('div'); run_div.className = 'whatever'; run_div.textContent = 'whatever'; run_div.setAttribute('ng-mouseover', 'console.log(&b ...

Hide the dropdown menu when the user clicks anywhere else on the screen

I have a scenario with 2 dropdown buttons. When I click outside the dropdown or on it, it closes. However, if I click on the other dropdown button, it does not close and the other one opens. I want them to close when I click on the other button or anywhere ...

Refresh Twitter Bootstrap Tooltip after deactivating/removing

I have a quick question. I am currently dealing with data that is constantly changing and displayed from a selected item in a table. To monitor for overflow, I have implemented the following code: if (event.target.offsetWidth < event.target.scrollW ...

I am having trouble getting event handlers to work with a group of buttons in JavaScript

I'm facing a problem where I'm attempting to add event handlers to buttons stored in an array. Upon clicking a button, it should trigger a function, but for some reason, it's not working and I can't seem to identify the issue. Below is ...

Node.js always returns an empty req.body

const server = express(); server.use(express.json()); server.use(express.urlencoded({ extended: true })); server.post("/", (req, res) => { res.status(200).json(req.body); }); receiving empty object consistently I am utilizing Thunder ...

The initial Mongoose stream fetches only a handful of results on its first

I am currently developing a cutting-edge real-time news service, but I have encountered an issue that is stumping me. Upon a user connecting to the NodeJS server, I establish a Mongoose stream to efficiently and quickly return data. The current problem I ...

Creating a primary php file in Apache without the use of SQL or any database: is it possible?

Forgive me if this comes across as rude, but I'm struggling to grasp the concept of apache, PHP, and servers in general. To help myself understand better, I want to create a very basic website that assigns an ephemeral ID to each user (not a session). ...

Exploring the Power of AngularJS within Confluence

I am facing an issue with AngularJS integration in Confluence. I attempted to incorporate angular files as web resources in the atlassian-plugin.xml file: <web-resource name="Angular js files" key="angular-sources"> <resource type="download" ...

Retrieving all embedded documents in MongoDB using Ruby on Rails

I'm struggling with a basic Mongo / Rails query related to the Leagues Model that embeds Teams. I want to retrieve a list of all teams across all leagues, but I can't seem to get it right. Can someone provide some guidance? Here's what I&ap ...

Adequate parameters are necessary for an express callback function beyond just (req, res)

Working on my express app, I've come across a requirement where only (req, res, next, err) can be passed into the callbacks. This is what I had that worked. function listEvents(auth, req, res, email, authURL = ""){ ... var calendar = google.calendar ...

Saving a picture to local storage with the file input type in ReactJS

I am attempting to save an image in the browser storage once a user selects an image from their computer. <div className="add_grp_image_div margin_bottom"> <img src={img_upload} className="add_grp_image"/> <input type="file" class ...

After refreshing the page, Google Chrome finally displays the CSS styles correctly

I'm currently working on a JavaScript script to showcase images on a webpage. These images are loaded using an AJAX request and a CSS style is directly applied using jQuery. The script functions correctly on Firefox, Opera, and IE, but Google Chrome i ...

Get every possible combination of a specified length without any repeated elements

Here is the input I am working with: interface Option{ name:string travelMode:string } const options:Option[] = [ { name:"john", travelMode:"bus" }, { name:"john", travelMode:"car" }, { name:"kevin", travelMode:"bus" ...

Accessing store state in axios plugin with Nuxt.js

I've encountered a problem where I have a token stored, but I'm struggling to access it in my axios plugin while using Nuxt.js. In the past with just Vue, it was simple to import the store and access the token. However, I'm having difficulty ...

How to troubleshoot the error I am encountering in Vue while using custom HTML tags?

While I'm still a Vue newbie, I find it quite enjoyable. I've been experimenting with using just a custom tag like this: <ui-button>Learn more</ui-button> Unfortunately, I encountered an error asking me to register the component. To ...

Retrieve JSON information using AngularJS

Here is the JSON file I'm working with: { "countries":[ { "country": "India", "cities" : [{ "name": "Bangalore", "rank": "40" }, { "name": "Mumbai", "rank": "32" }, ...