Muhammad Yusuf Malik
Muhammad Yusuf Malik

Reputation: 157

How to sum data after remove duplicate ($addToSet) mongoose aggregate

i have struggle to sum value after remove duplicate in mongoose. i have data like this:

{
            "_id": "6006c7f624d9e1364051b0aa",
            "paidFrom": "5fec1b5d124c58c6ddacfd02",
            "amount": 234,
        },
        {
            "_id": "600e63f2545087cbddfe370a",
            "paidFrom": "5fec1b5d124c58c6ddacfd02",
            "amount": 25000,
        },
        {
            "_id": "600e7c16545087cbddfe370b",
            "paidFrom": "5ff56473609e930518cb7b67",
            "amount": 5000,

        },

i want to remove duplicate data using aggregation, i want to sum by the same paid from value.

this is my code:

const dataAP = await AccountPayment.aggregate([
      { 
          $match: filterDate
      },
      {
        $group: {
            _id:  null,
            paidFrom: {
              "$addToSet" : "$paidFrom",
            },
            amount: {$sum: "$amount"}
        }
    },
    ], 
      function (err, res)
      {
          if (err) {} 
            console.log(err)
      });

but that code give me result:

"status": "success",
    "data": [
        {
            "_id": null,
            "paidFrom": [
                "5ff56473609e930518cb7b67",
                "5fec1b5d124c58c6ddacfd02",
                "5ff54212609e930518cb7b65"
            ],
            "amount": 60234
        }
    ]
}

my expected result is:

"status": "success",
    "data": [
        {
            "_id": null,
            "paidFrom": [
                "5ff56473609e930518cb7b67",
            ],
            "amount": 20000
        },
{
            "_id": null,
            "paidFrom": [
                "5fec1b5d124c58c6ddacfd02",
            ],
            "amount": 20000
        },
{
            "_id": null,
            "paidFrom": [
                "5ff54212609e930518cb7b65",
            ],
            "amount": 20234
        },
    ]


}

i want amount is sum by duplicate value, so i can calculate the duplicate value. can someone tell me whats wrong? thanks

Upvotes: 1

Views: 78

Answers (1)

turivishal
turivishal

Reputation: 36154

You just need to group by paidFrom id and sum amount, it will group duplicate documents and sum total amount

const dataAP = await AccountPayment.aggregate([
  { $match: filterDate },
  {
    $group: {
      _id: "$paidFrom",
      amount: { $sum: "$amount" }
    }
  }
], 
function (err, res) {
  if (err) console.log(err);
})

Playground

Upvotes: 1

Related Questions