I have a collection in mongo that looks like this:
{
"_id" : ObjectId("5c98d6f383d67f243730443b"),
"date" : ISODate("2019-03-24T00:00:00Z"),
"symbol" : "F:ABCD",
"symbolCode" : "wcgahi8gap",
"close" : 8.09,
"high" : 24.82,
"low" : 8.09,
"numPoints" : 8,
"open" : 20.84,
"volume" : 21183
}
{
"_id" : ObjectId("5c98d6f383d67f243730443c"),
"date" : ISODate("2019-03-25T00:00:00Z"),
"symbol" : "F:ABCD",
"symbolCode" : "wcgahi8gap",
"close" : 1.77,
"high" : 23.47,
"low" : 1.77,
"numPoints" : 3,
"open" : 8.21,
"volume" : 9645
}
Which shows the prices of stocks at end of day. I'm trying to write an aggregation to calculate the change/percent change for each stock in the 1 day interval. So it should just be the difference between the current days close field and the previous day close field. How can I do this?
This is what I have so far:
const results = await Price.aggregate([
{ $match: { date: { $gte: yesterday } } },
{ $sort: { date: 1 } },
{ $group: { '_id': '$_id',
'old': {
$sum: { $cond: [{ '$eq': [ '$date', yesterday ] }, '$close', 0] }
},
'new': {
$sum: { $cond: [{ '$eq': [ '$date', today ] }, '$close', 0] }
} } },
{ $project: { date: 1, symbol: 1, difference: { $subtract: ['$new', '$old'] } } }
])
I know I'm missing an important part of the group stage but I can't figure it out.