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

时间:2021-02-28 04:35:15

标签: mongodb mongodb-query

如果我有一个名为 game 的集合,它具有这样的架构。

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

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

SQL 等价物是。

SELECT * FROM game where points > opp_points;

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

1 个答案:

答案 0 :(得分:1)

$expr 中使用 $match 进行聚合或在 $find

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

聚合Mongo playground

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

工作 Mongo playground 的查找