I have a collection of docs like
{'id':1, 'score': 1, created_at: ISODate(...)}
{'id':1, 'score': 2, created_at: ISODate(...)}
{'id':2, 'score': 1, created_at: ISODate(...)}
{'id':2, 'score': 20, created_at: ISODate(...)}
etc.
Does anyone know how to find docs that were created within the past 24hrs where the difference of the score
value between the two most recent docs of the same id
is less than 5?
So far I can only find all docs created within the past 24hrs:
[{
$project: {
_id: 0,
score: 1,
created_at: 1
}
}, {
$match: {
$expr: {
$gte: [
'$created_at',
{
$subtract: [
'$$NOW',
86400000
]
}
]
}
}
}]
Any advice appreciated.
Edit: By the two most recent docs, the oldest of the two can be created more than 24hrs ago. So the most recent doc would be created within the past 24hrs, but the oldest doc could be created over 24hrs ago.
2
Answers
If I’ve understood correctly you can try this query:
$match
as you have to get documents since a day ago.$sort
by the date to ensure the most recent are on top.$group
by theid
, and how the most recent were on top, using$push
will be the two first elements in the array.$sum
these two values.$lt
) 5.Example here
Edit: $firstN is new in version 5.2. Other way you can use
$slice
in this way.If I understand you correctly, you want something like:
See how it works on the playground example
EDIT:
according to you comment, one option is:
See how it works on the playground example