Home > Blockchain >  Not getting same amount and same date row in group by date mongodb aggregation
Not getting same amount and same date row in group by date mongodb aggregation

Time:07-13

I have a data like this in MongoDB Collection

{
 date: '2022-07-09', //YYYY-MM-DD
 amount: 54.77
}
  
{
 date: '2022-07-21',
 amount: 50.20
}
  
{
 date: '2022-07-21',
 amount: 50.20
}
  
{
 date: '2022-06-26',
 amount: 54
}
  
{
 date: '2022-06-06',
 amount: 37
}
  
{
 date: '2022-06-06',
 amount: 37
}
  
{
 date: '2022-06-09',
 amount: 51.77
}

and I have a group query aggregation like this

match = { // some match query}
group = {
 _id: { month: { $substr: ['$date', 5, 2] }, year: { $substr: ['$date', 0, 4] } },
 amount: { $sum: "$amount" },
 transactions: { $addToSet: "$$ROOT"}
 }

I am grouping by month wise. The problem is when there is same date and amount data then its returning 1 row instead of 2 or 3. Sum of amount is giving fine but not getting all rows. Any help or idea ? Thanks in advance!!

CodePudding user response:

$addToSet will create a set, meaning no identical items. $push will insert to an array, meaning identical items are allowed:

group = {
 _id: { month: { $substr: ['$date', 5, 2] }, year: { $substr: ['$date', 0, 4] } },
 amount: { $sum: "$amount" },
 transactions: { $push: "$$ROOT"}
 }

See how it works on the playground example

  • Related