MongoDB查询条件包括SUM

时间:2015-11-02 15:20:28

标签: mongodb mongodb-query aggregation-framework

我如何使用mongo编写此sql查询?

select * from a where b + c < 5?

1 个答案:

答案 0 :(得分:1)

$redactaggregation 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的shell快捷方式),因此效果不佳:

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评估更高效。