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

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

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!!

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

>Solution :

$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

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