在你的SQL中你有:m_time-m_latency
,我认为这意味着从另一列中减去一列。
简短的回答:
这是不是你可以使用MongoDB的代表查询还因为你只能比较静态值的字段。
长的答案:
如果你想查找文档,其中m_time - m_latency + LATENCY_DELTA
是在特定的范围内,那么你将不得不存储值预先计算的文档的另一场。如果你这样做,那么你就可以简单地运行与查询:
db.collection.find({ 'm_calculated_latency' : { '$gte' : FROM_RANGE, '$lte' : TO_RANGE } });
或者在PHP中:
$collection->find(array(
'm_calculated_latency' => array(
'$gte' => $from_range,
'$lte' => $to_range,
)
)
解决方法:
随着MongoDB的聚合框架,你也许可以做到像你想要的查询,但它将不会是最快或最优雅的解决方案,也不会使用索引。所以请重新设计您的模式并添加预先计算的字段。
与警告的方式进行,这里有云:
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 } }
]);
在$项目一步,我们计算场时间m_time - m_latency + DELTA
。我们还输出原始的m_time
和m_latency
字段。然后在$匹配步骤中,我们将计算的time
与FROM
或TO
进行比较。最后我们按计算的time
排序。 (因为你的原始SQL排序也没有意义,我假设你打算按时差排序)。
用我的输入数据:
> 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
这将产生:
{
"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
}
现在最后绝招是写从上面的PHP语法的汇总查询,正如你所看到的用处不大:
<?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);
?>
你会得到什么错误? –
查询不运行。我很确定查询中有错误。 (我没有做ORDER BY,但是我写的查询中有错误,这是肯定的。如果有人能帮我指出那会很棒。 –
是的,但是你遇到了什么具体的错误。 Mondo和你没有得到任何结果,你是否看着你正在得到什么错误(即比“它不工作”更具体)? –