Sum values in project pipeline based on conditions with Mongo

I am currently implementing a project pipeline that involves filtering values greater than 100 from fields within an object that is part of an array. Here's an example of the database structure:

Database:

---Clients Collection---

client: {
    _id: 1,
    taxID: aldsfkjasdlñfk
    // other stuff
}

---Invoices Collection---

invoice: {
    _id: 1,
    clientID: 1,
    total: 50
},
invoice: {
    _id: 2,
    clientID: 1,
    total: 150
},
invoice: {
    _id: 3,
    clientID: 1,
    total: 200
}

THIS IS MY CURRENT QUERY:

{
     $lookup: {
          from: 'invoices',
          localField: '_id',
          foreignField: 'client.id',
          as: 'invoices'
     }
},
{
     $project: {
          id: 1,
          taxID: aldsfkjasdlñfk,
          invoicesAmountGreaterThanOneHundred: {
               $sum: {
                   $cond: { if: { $gte: ['$invoices.total', 100] }, then: '$invoices.total', else: 0 }
               }
          }
     }
}

The expected output should be:

{
     _id: 1,
     taxID: aldsfkjasdlñfk,
     invoicesAmountGreaterThanOneHundred: 350
}

I am using MongoDB version 3.6.3.

In the future, I also plan to incorporate "invoicesAmountLesserThanOneHundred" following a similar approach for values lesser than 100.

Answer №1

Always remember to apply the $filter function before using $sum

db.client.aggregate([
  {
    $lookup: {
      from: "invoices",
      localField: "_id",
      foreignField: "clientID",
      as: "invoices"
    }
  },
  {
    $set: {
      "invoices": {
        "$filter": {
          "input": "$invoices",
          "as": "i",
          "cond": { $gte: [ "$$i.total", 100 ] }
        }
      }
    }
  },
  {
    $project: {
      id: 1,
      taxID: 1,
      invoicesAmountGreaterThanOneHundred: {
        $sum: "$invoices.total"
      }
    }
  }
])

Explore more on mongoplayground


Utilize the $reduce method for efficiency

db.client.aggregate([
  {
    $lookup: {
      from: "invoices",
      localField: "_id",
      foreignField: "clientID",
      as: "invoices"
    }
  },
  {
    $set: {
      "invoicesAmountGreaterThanOneHundred": {
        $reduce: {
          input: "$invoices",
          initialValue: "",
          in: {
            $sum: [
              "$$value",
              {
                $cond: {
                  if: { $gte: [ "$$this.total", 100 ] },
                  then: "$$this.total",
                  else: 0
                }
              }
            ]
          }
        }
      }
    }
  }
])

Check out the functionality on mongoplayground

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

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

CryptoJS consistently produces identical hash values for distinct files

Utilizing CryptoJS to generate a hash value for uploaded files has presented me with a challenge. Despite my efforts, all files I upload seem to produce identical hash values. It appears that the issue lies within my "onFileChange" function, but pinpointin ...

Struggling to correctly showcase my Firebase data in Angular using the orderByChild method

I have a user database structured like this : Database - Users - Id (generated using the push method) - email - firstName - ptsTotal - ... I am looking to create a ranking of users based on their total points (ptsTotal) in a game using ...

Issue with displaying entire object using Jest and console.dir

I'm having trouble displaying an error in my Jest test because it's not showing all the levels as expected. import util from 'util' describe('Module', () => { it('should display all levels WITHOUT util', () =& ...

Adding parameters to a URL is a common practice

"Adding additional information to a URL that was previously included?" I apologize for the confusing title, but I can't find a better way to phrase it. Perhaps an example will make things clearer. Let's say I have URL 1: http://example.com/?v ...

The SWT Browser is failing to display Angular 2 pages within the Eclipse view

I attempted to embed Angular 2 HTML pages within the SWT Browser widget, but it seems that the Angular 2 HTML pages are not displaying correctly inside the SWT Browser. However, I had no trouble embedding Angular 1 (or Angular JS) pages within the SWT bro ...

Changing the counter using dual buttons in Vue.js

I am facing an issue with updating the counter when using both the add and remove buttons. The add button functions correctly, but unfortunately, the delete button does not update the counter as expected. Below is a picture showcasing the problem at hand: ...

Laravel relationships and type casting

Currently working on a survey platform where users rate from 0 to 10. I'm testing out using casts to store questions and answers in a single row. Here's a glimpse of how the scores field appears in the database: {"5":8,"6":8} This setup is wor ...

Is there a way to mimic this type of scrolling effect?

Upon visiting this website, it is evident that the entire interface has been constructed with React. The scrolling experience on this site is exceptionally smooth, although it may feel slightly more substantial than a typical scroll. After researching onli ...

Traversing through pair of arrays simultaneously using forEach loop in JavaScript

I am trying to create a for loop that simultaneously iterates through two variables. One is an array named n, and the other, j, ranges from 0 to 16. var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; ...

jPages fails to recognize dynamically added images using jQuery in real-time

I have a HTML and JS script that is designed to load images from PHP using AJAX and then place them into a div. Afterwards, a JavaScript function will paginate the images. Everything works perfectly fine when I hardcode the images manually. However, when I ...

"Creating a dynamic Map using the HERE Maps API and adjusting its size: A step-by-step guide

I am currently working on a Website project and I am interested in incorporating an interactive map from HERE Maps that spans the entire screen under my navigation bar. How can I achieve this? After initially using Google Maps, I switched to HERE Maps due ...

How many files are being monitored by Grunt?

Recently, I received a new project using Angular + Node from a client and successfully set it up on my local machine. However, one major issue arose when running the grunt command - my CPU spiked to 100% causing my system to hang. Strangely, the same proje ...

Commit the incorrect file name with the first letter capitalized

There seems to be an issue with the git not recognizing the correct filename casing. I have a file named User.js in my workspace, but when checking the git status, it displays user.js instead. Despite repeatedly changing and committing as User.js, the gi ...

What is the best way to combine duplicate JSON objects together?

I am facing a challenge with my json data structure, shown below: [{ "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100}", "displayOn": "true", "attributeName": "price" }, { "attributeId": 6, "attribu ...

I'm currently working with ReactJS and attempting to retrieve JSON data from a REST API in JIRA, but I'm facing challenges in achieving this

I've been struggling for hours trying to understand why I am unable to access and transfer data in my array from the JSON data in JIRA using the REST API. Basically, I am attempting to retrieve the JSON data from the JIRA website via URL with Basic Au ...

The positioning of the Kendo UI window is off-center

I have encountered a problem with the alignment of the Kendo Window. There is a simple fiddle available to demonstrate this issue. Despite having ample space for the Kendo window to show without triggering the browser's vertical scroll bar, the cente ...

Is it possible to enforce data types for fields in MongoDB?

Following up on the issue raised in this post: It seems like the underlying problem is that certain fields are stored as Double instead of Long. Is there a method to enforce datatype for specific fields in MongoDB? I would like the document insertion t ...

Consistently obtaining the same outcome in JavaScript, always

Is it possible to resolve this issue? I keep getting a result of less than 18 when trying numbers 1-100, even though the output should be for values under 18. In my HTML code, there is a <p> element with id="result", an input with id=&quo ...

Using ng-pattern to validate that a text field does not conclude with a particular term

In this code snippet, I am attempting to prevent a textfield from ending with any of the specified letters in the $scope.pointPattern variable. $scope.pointPattern = /^(?!.*ess|ence|sports|riding?$)/; $scope.error = "not valid"; Upon executio ...