You can easily convert documents using the aggregation and cursor iteration structures.
Example:
db.collection.aggregate([ {$project: { value:1, "threshold":{$let: { vars: {threshold: 80 }, in: "$$threshold" }} } }, {$match:{value:{$ne: "$threshold"}}}, {$group: { _id:"$null", low:{ $max:{ $cond:[{$lt:["$value","$threshold"]},"$value",-1] } }, high:{ $min:{ // 10000000000 is a superficial value. // need something greater than values in documents $cond:[{$gt:["$value","$threshold"]},"$value",10000000000] } }, threshold:{$first:"$threshold"} } } ])
The aggregation structure will return a document with two values.
{ "_id" : null, "low" : NumberInt(75), "high" : NumberInt(81), "threshold" : NumberInt(80) }
We can easily find documents that meet your return criteria. for example, in NodeJS we can easily do this. assuming the result variable contains the result of the aggregation request.
result.forEach(function(r){ var documents = []; db.collection.find({$or:[{"value": r.low},{"value": r.high}]}).forEach(function(doc){ var _doc = {}; _doc.time = doc.time; _doc.result = doc.value < r.threshold ? "enter" : "exit"; documents.push(_doc); }); printjson(documents); });
As you remember, if your input documents (sample)
{ 'time' : '2016-03-28 12:12:00', 'value' : 90 }, { 'time' : '2016-03-28 12:13:00', 'value' : 82 }, { 'time' : '2016-03-28 12:14:00', 'value' : 75 }, { 'time' : '2016-03-28 12:15:00', 'value' : 72 }, { 'time' : '2016-03-28 12:16:00', 'value' : 81 }, { 'time' : '2016-03-28 12:17:00', 'value' : 90 }, etc....
The request above in the solution will emit:
{ "time" : "2016-03-28 12:14:00", "result" : "enter" }, { "time" : "2016-03-28 12:16:00", "result" : "exit" }