Lets say I have a collection of documents like:
[
{ "createdAt": 1688383980100, "win": true },
{ "createdAt": 1688383980200, "win": false },
{ "createdAt": 1688383980300, "win": true },
{ "createdAt": 1688383980400, "win": true },
{ "createdAt": 1688383980500, "win": false }
]
How can I get the longest/max win streak? I managed to get it via $group and $accumulator with custom JS functions. But Digital Ocean does not allow JS on their Mongo DB instances.
So I spent almost a day trying many pipeline alternatives, including many combinations of aggregators like $group, $project, $setWindowFields, with $sum, $max, $cond, $multiply, etc.
Read a lot of articles, SO questions, searched the docs, talked a lot to chatGPT, no success. Any tips or pointers are super welcome! Thanks in advance!
If you don't want to group your entire collection (which is not recommended), you can use
setWindowFields:setWindowFieldsto mark documents which ends a win streak (so we can filter out allwin: falsedocuments)$matchto keep only "winning" documents, now that we have our mark$matchto keep only documents which ends a win streak, now that we have our indexsetWindowFieldsto insert the index for the previous streak end$sortand$limitthe find the maximal valueSee how it works on the playground example
This method allows to avoid grouping all documents into one large document (which has a size limit). It uses a pipeline that reduces the number of documents throughout the calculation.
If you can assume the maximal win streak is less than a reasonable number, (for example: 100), you can do it much simpler, using only one
$setWindowFieldsstep, by keeping the last 100 documents wins on each document...