【问题标题】:mongoose aggregate $convert fieldname with spacesmongoose 聚合 $convert 带空格的字段名
【发布时间】:2021-05-15 20:12:55
【问题描述】:

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

但输入字段 $+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,这是不正确的结果。

【问题讨论】:

    标签: string mongoose double aggregate


    【解决方案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"
      }
    ]
    

    【讨论】:

    • 谢谢,确实也可以使用$toDouble,我在字段名中发现了一个错误,它是来自子文档的字段,所以我需要将子文档名称添加到我的查询$ + 'payload 。 + fieldName .. :) 现在它工作得很好!
    猜你喜欢
    • 2021-11-20
    • 2021-08-26
    • 2015-05-18
    • 2019-03-30
    • 2012-09-28
    • 2017-11-27
    • 2018-03-29
    • 1970-01-01
    • 2020-10-10
    相关资源
    最近更新 更多