有没有办法比较 MongoDB 查询中的两个字段

unl*_*d_J 2 mongodb mongodb-query

如果我有一个名为 game 的集合,其架构如下。

{"team": "A", "opponent": "B", "points": 101, "opp_points": 100}
{"team": "B", "opponent": "A", "points": 100, "opp_points": 101}
Run Code Online (Sandbox Code Playgroud)

有没有办法查询同一集合中两个字段之间的比较?

SQL 的等价物是:

SELECT * FROM game where points > opp_points;
Run Code Online (Sandbox Code Playgroud)

我浏览了 Mongo 的文档并没有找到这个,但我认为他们可能有它。

var*_*man 8

$expr$match聚合或 in 中使用$find

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          "$points",
          "$opp_points"
        ]
      }
    }
  }
])
Run Code Online (Sandbox Code Playgroud)

聚合的工作Mongo 游乐场

db.collection.find({
  $expr: {
    $gt: [
      "$points",
      "$opp_points"
    ]
  }
})
Run Code Online (Sandbox Code Playgroud)

find 的工作Mongo 游乐场