Is there a way to compare two fields in a MongoDB query

Viewed 3292

If I have a collection called game that has a schema like this.

{"team": "A", "opponent": "B", "points": 101, "opp_points": 100}
{"team": "B", "opponent": "A", "points": 100, "opp_points": 101}

Is there a way to query on a comparison between two fields in the same collection?

The SQL equivalent would be.

SELECT * FROM game where points > opp_points;

I have looked through Mongo's documentation and haven't found this, but thought they probably have it.

1 Answers

Use $expr in $match in aggregation or in $find

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          "$points",
          "$opp_points"
        ]
      }
    }
  }
])

Working Mongo playground of aggregation

db.collection.find({
  $expr: {
    $gt: [
      "$points",
      "$opp_points"
    ]
  }
})

Working Mongo playground of find

Related