Database
[{"events":[{"name":"A"},{"name":"C"},{"name":"D"},{"name":"B"},{"name":"E"}]},{"events":[{"name":"A"},{"name":"B"},{"name":"S"},{"name":"C"}]}]
Query
db.collection.aggregate([{$addFields:{count:[]//addanemptyarraytostoretheresults}},{$match:{events:{name:"A"}}},{/* Count replace all documents so a facet is used to keep the documents
in the other part of the facet we are slicing to the matched event
+1 so we do not include it */$facet:{count:[{$count:"value"}],sliceToMatchedEvent:[{$set:{events:{$slice:["$events",{$add:[{$indexOfArray:["$events.name","A"]},1]},200]}}}],}},/* The 3 folling step are used to reshape the document to the original
shape so we can iterate with the next event it the sequence we want to match*/{$unwind:"$sliceToMatchedEvent"},{$unwind:"$count"},{$replaceRoot:{newRoot:{$mergeObjects:["$sliceToMatchedEvent",{count:{$concatArrays:["$sliceToMatchedEvent.count",["$count.value"]]}}]}}},{$match:{events:{name:"B"//Changethisvaluetosomethingnotitthearray}//totriggertheun·de·siredbehavioreg:"Z"}},{$facet:{count:[{$count:"value"}],sliceToMatchedEvent:[{$set:{events:{$slice:["$events",{$add:[{$indexOfArray:["$events.name","B"]},1]},200]}}}],}},{$unwind:"$sliceToMatchedEvent"},{$unwind:"$count"},{$replaceRoot:{newRoot:{$mergeObjects:["$sliceToMatchedEvent",{count:{$concatArrays:["$sliceToMatchedEvent.count",["$count.value"]]}}]}}}])