Mongodb count the number of consecutive matching docs and merge them into one

I agree with @Pavel_Duchovny,

it looks like you just need to adjust your schema to have 2 types of documents:

  1. ‘Regular’ document with all the properties you’ve mentioned
  2. A Bucket document that will contain metadata and an array of the specific elements together with numConsecutiveItems property that will be updated manually or by $size operation on the array.

anyway, it looks like you need a solution that will be partially managed by the application on the writes, and easily fetch on reading.

the only restriction in the solution I have suggested is that the array shouldn’t contain too many elements (I think the magic number is ~1000 and above)