Skip to content
Advertisement

Mongodb Compare two fields with ratio

Rows whose field is twice that of the other field explain with example :

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

I want row that spend is equal or bigger twice price (spent >= 2*price)

result :

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

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

please refer suggestion except use $where

my mongo cluster have limitations of use $where

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

Advertisement

Answer

MongoDB documentation is very good with examples.
There is a place Reference that has all the operators.
If you haven’t found it, maybe try the bellow, i think this is what you need.

Query

  • we can refer to the field with $fieldName
  • and gt/multiply operators are used
  • finally $expr is used in match when we use aggregate operators (instead of query operaros) like we did here

Playmongo

aggregate(
[{"$match": {"$expr": {"$gt": ["$spent", {"$multiply": [2, "$price"]}]}}}])
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement