首页 > 解决方案 > mongoose 聚合 $convert 带空格的字段名

问题描述

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

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

有人有解决方案吗?

示例数据

{_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,这是不正确的。

标签: stringmongoosedoubleaggregate

解决方案


您可以使用$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"
  }
]

推荐阅读