Database
[{code:"1",results:{winCode:3}},{code:"10",results:{winCode:3}},{code:"8",results:{winCode:2}},{code:"5",results:{winCode:5}},{code:"5",results:{winCode:4}},{code:"6",results:{winCode:4}},{code:"7",results:{winCode:5}},{code:"3",results:{winCode:3}},{code:"9",results:{winCode:2}},{code:"2",results:{winCode:2}}]
Query
db.collection.aggregate([{$setWindowFields:{sortBy:{code:-1},output:{index:{$sum:1,window:{documents:["unbounded","current"]}}}}},{$sort:{code:-1}},{$group:{_id:"$results.winCode",count:{$sum:1},lastTimeOccurredCode:{$first:"$code"},index:{$push:"$index"}}},{$project:{count:1,lastTimeOccurredCode:1,diff:{$reduce:{input:{$range:[1,{$size:"$index"}]},initialValue:[],in:{$concatArrays:["$$value",[{$subtract:[{$arrayElemAt:["$index","$$this"]},{$arrayElemAt:["$index",{$subtract:["$$this",1]}]}]}]]}}}}},{$set:{minRecordsBetween:{$min:"$diff"},maxRecordsBetween:{$max:"$diff"},diff:"$$REMOVE"}},{$sort:{_id:-1}}])