猫鼬用空格聚合 $convert 字段名

时间:2021-02-12 02:40:14

标签: string mongoose double aggregate

我正在尝试将字符串字段转换为 double,同时聚合包含空格的字段名称。

但输入字段 $+sumField 解析为带有空格的 $Total Incl Vat,我认为这是不正确的,它不会返回实际总和。< /p>

有人有解决方案吗?

示例数据

{_id: 1, "Total Incl Vat": "1550.96", customer: 1},
{_id: 2, "Total Incl Vat": "2000", customer: 1},
{_id: 3, "Total Incl Vat": "1000", customer: 1}

聚合

 const sumField = "Total Incl Vat";
 const $group = { 
                _id: null,
                total: {
                    $sum: {
                        $convert: {     
                            input: "$" + sumField,
                            to: 'double',
                            onNull: 0,
                            onError: "Error"
                        } 
                    }
                }
            }

 const result = mycollection.aggregate([
     { $match: { customer: 1 }}, 
     { $group }
 ]);

聚合结果为 0 作为结果不正确。

1 个答案:

答案 0 :(得分:1)

您可以使用 $toDouble 运算符。这是您要查找的聚合:

mycollection.aggregate([
  {
    $match: {
      customer: 1
    }
  },
  {
    "$group": {
      _id: null,
      total: {
        "$sum": {
          $toDouble: "$Total Incl Vat"
        }
      }
    }
  }
])

游乐场:https://mongoplayground.net/p/ItjKc31TSyi

如果你只想用美元符号显示总数,你可以像这样进一步投影:

  {
    "$project": {
      _id: false,
      total: {
        "$concat": [
          {
            $literal: "$"
          },
          {
            "$toString": "$total"
          }
        ]
      }
    }
  }

这将导致:

[
  {
    "total": "$4550.96"
  }
]