mongodbmongodb-querypymongomongo-collection

Is there a way to filter a MongoDB document by other values within that document?


I have a document I'm trying to filter with rows created by aggregation functions that look like:

{
   "_id": {
      "ID": "randNum01"
   },
   "ImportantVal1": 50,
   "importantVal2": 22
}

{
   "_id": {
      "ID": "randNum02"
   },
   "ImportantVal1": 40,
   "importantVal2": 100
}

{
   "_id": {
      "ID": "randNum03"
   },
   "ImportantVal1": 60,
   "importantVal2": 2
}

How could I use an aggregation function to only choose the rows where importantVal1 > importantVal2?

I'm currently trying something like:

{
   "$match": {
      "ImportantVal1": {
         "$gt": "$importantVal2"
      }
   }
}

but it returns nothing


Solution

  • Try this :

    {$match:{$expr:{$gt:["$ImportantVal1", "$ImportantVal2"]}}}
    

    Check out $expr for more information.