2015-11-02 116 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評估更具性能。