Use the following aggregation pipeline which does an initial $match to filter out those documents that are less than 60.
The next pipeline step uses the $sort operator to re-order the documents by the time field which is necessary for the next step, i.e. the $group pipeline. In here that's where you derive the start and end fields through the use of the $first and $last accumulator operators that extract the first and last times when you group the documents by the speed field as the key.
The last pipeline step $project creates the additional field, duration using the $subtract arithmetic operator which, as the name implies, subtracts the start from the end times. The final pipeline would look like this:
db.test.aggregate([
{ "$match": { "speed": { "$gte": 60 } } },
{ "$sort": { "time": 1 } },
{
"$group": {
"_id": "$speed",
"start": { "$first": "$time" },
"end": { "$last": "$time" }
}
},
{
"$project": {
"_id": 0,
"speed": "$_id",
"duration": { "$subtract": [ "$end", "$start" ] },
"start": 1,
"end": 1
}
}
])
Sample Output:
/* 0 */
{
"result" : [
{
"start" : 1446271010,
"end" : 1446271010,
"speed" : 67,
"duration" : 0
},
{
"start" : 1446271007,
"end" : 1446271007,
"speed" : 61,
"duration" : 0
},
{
"start" : 1446271008,
"end" : 1446271008,
"speed" : 62,
"duration" : 0
},
{
"start" : 1446271004,
"end" : 1446271004,
"speed" : 70,
"duration" : 0
},
{
"start" : 1446271003,
"end" : 1446271003,
"speed" : 68,
"duration" : 0
},
{
"start" : 1446271002,
"end" : 1446271009,
"speed" : 63,
"duration" : 7
}
],
"ok" : 1
}