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

How to get sum of values in array of objects in mongodb

i have a mongodb recor which looks like this .

[
  {
    "_id": {
      "$oid": "64a5a396ec152ab4f5e1c60c"
    },
    "firstName": "Ram",
    "lastName": "Shayam",
    "email": "abc@123.com",
    "transactions": [
      {
        "amount": 22,
        "date": "21/7"
      },
      {
        "amount": 12,
        "date": "21/7"
      },
      {
        "amount": 50,
        "date": "19/7"
      },
      {
        "amount": 100,
        "date": "19/7"
      }
    ]
  }
]

now i gave to filter transactions on the basis of date by doing these operations:

db.collection.aggregate([
  {
    $match: {
      firstName: "Ram"
    }
  },
  {
    $unwind: "$transactions"
  },
  {
    $match: {
      "transactions.date": {
        $eq: "21/7"
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      list: {
        $push: "$transactions"
      }
    }
  }
])

and getting shorted array with transactions of only given dates like this…

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

[
  {
    "_id": ObjectId("64a5a396ec152ab4f5e1c60c"),
    "list": [
      {
        "amount": 22,
        "date": "21/7"
      },
      {
        "amount": 12,
        "date": "21/7"
      }
    ]
  }
]

**now how to get the total amount spend on that day using some other operations.
like i want to get 34 as output by doing operations.

here is the playground link for more details.**

how to get the total amount spend on that day using some operations from a array of objects with amount and date of amount.

>Solution :

Use $sum(aggregation)

db.collection.aggregate([
  {
    $match: {
      firstName: "Ram"
    }
  },
  {
    $unwind: "$transactions"
  },
  {
    $match: {
      "transactions.date": {
        $eq: "21/7"
      }
    }
  },
  {
    $group: {
      _id: "$_id",
      list: {
        $push: "$transactions"
      },
      total: {
        $sum: "$transactions.amount"
      }
    }
  }
])

mongoplayground

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