Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongodb Aggregation: How to find remaining stocks

I want to find how much cost I have in remaining stocks.
It should filter out stock with remaining = 0

I have the following data

db={
  stocks: [
    {
      remaining: 2,
      costPerItem: 5
    },
    {
      remaining: 3,
      costPerItem: 2
    },
    {
      remaining: 0,
      costPerItem: 3
    }
  ]
}

I have created Mongo Playground: https://mongoplayground.net/p/d5S19t60V4B

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Total cash of each item is remaining * costPerItem

The expected result should return total cash in stock: 16

>Solution :

Group all documents, and sum the total of the result multiplying the remaining and costPerItem values.

db.stocks.aggregate([
  {
    $group: {
      _id: null,
      totalCashInStock: {
        $sum: {
          $multiply: [
            "$remaining",
            "$costPerItem"
          ]
        }
      }
    }
  }
])

Demo @ Mongo Playground

You could add a $match stage before the $group stage to filter the document with remaining not 0. It is optional as if remaining is 0, the outcome after multiplying with costPerItem will be 0, so technically the result will be the same as the aggregation query without $match stage.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading