I have a bunch of records in this format on mongodb
[
{_id: 1, date:'2023-07-28',sales:1,ad_id:1,status: 'Active'},
{_id: 2 , date:'2023-07-29',sales:2,ad_id:1,status: 'Active'},
{_id: 3, date: '2023-07-30',sales: 4,ad_id:1,status: 'Paused'}
]
Now if I want data from date 2023-07-28
to 2023-07-29
. I want sales to be summed but I want the status from latest record that is of 2023-07-30
. So In the end I want result something like this
{'ad_id': 1, sales: 3, status: 'Paused'}
.
On mysql it would be something like this
with ad as (
SELECT sum(sales) as totalSales,ad_id from table_name
where date >= '2023-07-28' and date <= '2023-07-29'
group by ad_id
)
SELECT * from ad left join (
SELECT id,ad_id,status from table_name where id in (
select max(id) from table_name group by ad_id
)
) t on t.ad_id = ad.ad_id
2
Answers
I’ll give a summary of what the following code is doing:
facet
to create two difference aggregates named assalesSum
andrecentStatus
salesSum
we are filtering on the date, then grouping onad_id
column and then extracting thesales
info from itrecentStatus
we are grouping onad_id
and figuring out the max of_id
column through grouping, then filtering it on themaxId
to get the recentstatus
using$push: "$$ROOT"
salesSum
andrecentStatus
tables using$unwind
ad_id
Code:
Try it on Mongo PlayGround
Here’s one way you could do it.
Try it on mongoplayground.net.