MongoDB 聚合 - 将字段解析为十进制并在匹配中使用它

MongoDB Aggregation - Parse field to decimal and use this in match

我有一个包含字符串类型余额字段的文档。

我想排除所有这些“余额”属性 为 $lte: 0 的文档,但我无法找到正确的语法。

$match:{
  {$toDecimal:'$balance'}: $lte:0
}

它不起作用。我想知道如何在进行匹配之前将字段转换为匹配函数中的数字。

你应该使用$expr,语法如下:

{
  $match: {
    $expr: {
      $lte: [
        { $toDecimal: '$balance' },
        0
      ]
    }
  }
}

Sample Mongo Playground