2015-11-02 118 views
-8

我如何用mongo写这个sql查询?MongoDB查询条件包括SUM

select * from a where b + c < 5? 
+0

搜索引擎是你的朋友:[SQL to Aggregation Mapping Chart](https://docs.mongodb.org/manual/reference/sql-aggregation-comparison/) –

+0

您还需要观看“autotag”功能堆栈溢出。交叉发布到“sql”和“nosql”标签不会赢得你的朋友。 –

回答

1

$redact运营商aggregation framework的是最好的选择:

db.collection.aggregate([ 
    { "$redact": { 
     "$cond": { 
      "if": { "$lt": [ { "$add": [ "$b", "$c" ] }, 5 ] }, 
      "then": "$$KEEP", 
      "else": "$$PRUNE" 
     } 
    }}, 
    { "$project": { "_id": 0, "a": 1 } } 
]) 

的逻辑条件,以确定保留哪个项目通过$lt上的$add数学表达式制作。

$project选择字段。

替代品是$where,它使用JavaScript评估。不是有效,由于需要翻译的JavaScript(以下是$where一个外壳程序快捷方式):

db.collection.find(
    function() { 
    return (this.b + this.c) < 5; 
    }, 
    { "_id": 0, "a": 1 } 
); 

或者:

db.collection.find(
    { "$where": "return (this.b + this.c) < 5;" }, 
    { "_id": 0, "a": 1 } 
); 

这基本上是同样的事情。

本机操作符比JavaScript评估更具性能。