Mongodb 比较两个字段的比率

Mongodb Compare two fields with ratio

字段是其他字段两倍的行 举例说明:

{id : 1 , price : 10 , spent : 5}
{id : 1 , price : 20 , spent : 30}
{id : 1 , price : 40 , spent : 90}
{id : 1 , price : 80 , spent : 200}

我想要花费等于或大于价格两倍的行(花费 >= 2*价格)

结果:

{id : 1 , price : 40 , spent : 90} ==> (花费 >= 2价格) [90>80]*

{id : 1 , price : 80 , spent : 200} ==> (花费 >= 2价格) [160>200]*

请参考建议,除了使用 $where

我的 mongo 集群有使用限制 $where

(MongoError: $where is not allowed in this atlas tier)

MongoDB 文档非常好,有示例。
有一个地方 Reference 有所有的运算符。
如果你还没有找到它,也许试试下面的方法,我想这就是你需要的。

查询

  • 我们可以用$fieldName
  • 来引用字段 使用了
  • 和 gt/multiply 运算符
  • 最后 $expr 在我们使用聚合运算符(而不是查询运算符)时用于匹配,就像我们在这里所做的那样

Playmongo

aggregate(
[{"$match": {"$expr": {"$gt": ["$spent", {"$multiply": [2, "$price"]}]}}}])