In your SQL you have: m_time-m_latency which I presume means subtract one column from another.
The short answer:
This is not something you can represent with MongoDB queries yet as you can only compare fields with static values.
The long answer:
If you want to find documents where m_time - m_latency + LATENCY_DELTA is in a specific range then you will have to store that value pre-calculated in another field of the document. If you do that, then you can simply run the query with:
db.collection.find( { 'm_calculated_latency' : { '$gte' : FROM_RANGE, '$lte' : TO_RANGE } } );
Or in PHP:
$collection->find( array(
'm_calculated_latency' => array(
'$gte' => $from_range,
'$lte' => $to_range,
)
)
The workaround:
With MongoDB's aggregation framework, you can probably do a query like you want, but it will by far not be the fastest or most elegant solution and neither does it use an index. So please redesign your schema and add that pre-calculated field.
With the warning out of the way, here goes:
FROM=3
TO=5
DELTA=1
db.so.aggregate( [
{ $project: {
'time': { $add: [
{ $subtract: [ '$m_time', '$m_latency' ] },
DELTA
] },
'm_time' : 1,
'm_latency' : 1
} },
{ $match: { 'time' : { $gte: FROM, $lte: TO } } },
{ $sort: { 'time' : 1 } }
] );
In the $project step, we're calculating the field time as m_time - m_latency + DELTA. We also output the original m_time and m_latency fields. And then in the $match step, we are comparing the calculated time with either FROM or TO. And lastly we sort by the calculated time. (As your original SQL sort didn't make sense either, I assumed you meant to sort by the time difference).
With my input data:
> db.so.insert( { m_time: 5, m_latency: 3 } );
> db.so.insert( { m_time: 5, m_latency: 1 } );
> db.so.insert( { m_time: 8, m_latency: 1 } );
> db.so.insert( { m_time: 8, m_latency: 3 } );
> db.so.insert( { m_time: 7, m_latency: 2 } );
> db.so.insert( { m_time: 7, m_latency: 4 } );
> db.so.insert( { m_time: 7, m_latency: 6 } );
> FROM=3
> TO=5
> DELTA=1
This produces:
{
"result" : [
{
"_id" : ObjectId("51e7988af4f32a33dac184e8"),
"m_time" : 5,
"m_latency" : 3,
"time" : 3
},
{
"_id" : ObjectId("51e7989af4f32a33dac184ed"),
"m_time" : 7,
"m_latency" : 4,
"time" : 4
},
{
"_id" : ObjectId("51e7988cf4f32a33dac184e9"),
"m_time" : 5,
"m_latency" : 1,
"time" : 5
}
],
"ok" : 1
}
Now the last trick is to write the aggregate query from above in PHP syntax, which as you can see is quite trivial:
<?php
$m = new MongoClient;
$db = $m->test;
$r = $db->so->aggregate( [
[ '$project' => [
'time' => [ '$add' => [
[ '$subtract' => [ '$m_time', '$m_latency' ] ],
$DELTA
] ],
'm_time' => 1,
'm_latency' => 1
] ],
[ '$match' => [ 'time' => [ '$gte' => $FROM, '$lte' => $TO ] ] ],
[ '$sort' => [ 'time' => 1 ] ]
] );
var_dump( $r );
?>
Multiple annotations found at this line: - syntax error, unexpected ',' - syntax error, unexpected '=>'But I am pretty sure that my the syntax i wrote is incorrect. Can you please correct my syntax.