Mongo过滤器:这些sql语句是否有等价物?

时间:2013-06-03 14:12:01

标签: mongodb pymongo

我需要在mongo过滤器中使用类似子查询的东西。像是说

Select * from table where column_1 < column_2

Select * from table where column_1 < (select max(column_1) from table)

上面的sql语句是否有mongodb等价物?

更新

阅读完文档后,我发现我可以使用mongo Select * from table where column_1 < column_2

$where

但我仍然不知道做Select * from table where column_1 < (select max(column_1) from table)

的答案

2 个答案:

答案 0 :(得分:2)

Select * from table where column_1 < (select max(column_1) from table)

实际上是一个非常简单的。 MongoDB中没有表格的投影,但幸运的是这个查询非常简单:

var max_doc=db.collection.find().sort({column_1:-1}).limit(1) ;
    // Will get to the row with the max value for column_1

if(mac_doc!==null)
    var result=db.collection.find({column_1:{$lt:max_doc['column_1']}})

对于初学者而言,这将比性能提高100倍,并且优于$where

第一个查询实际上可以使用聚合框架执行,最有可能使用$ cmp运算符:http://docs.mongodb.org/manual/reference/aggregation/cmp/

db.collection.aggregate([
    {$project: {_id:'$_id',s:{$cmp:['$column_1','$column_2']}}},
    {$match: {s:{$lt:0}}}
])

哪个也很可能比$where更好,即使是新的2.4更改(实际上只对MR有帮助)。

答案 1 :(得分:1)

您可以使用$where运算符。请参阅此内容以了解$where

的用法
相关问题