In time series data in ElasticSearch, need to find the count of documents till a point at which the value changes

Lets say there are documents such as below, with these fields

"time": X, "value": 1, "key": M
"time": X-1, "value": 1, "key": M
"time": X-2, "value": 1, "key": M
"time": X-3, "value": 1, "key": M
"time": X-4, "value": 1, "key": M
"time": X-5, "value": 0, "key": M
"time": X-6, "value": 1, "key": M
"time": X-6, "value": 1, "key": M

There are multiple such documents for other "key".

I want to find all documents that currently at time X have the "value": 1 and the number of times they have "value" as "1", before it changed to anything else, grouped by "key".

In this case, I would like to see something in the line of:

{
 "key": M,
 "count": 5
}