string - 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,这是不正确的。
解决方案
您可以使用$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"
}
]
推荐阅读
- linux - Vim 的行为在保存文件时有所不同
- linux - 更改 Linux 帧缓冲区的分辨率
- xml - 用python解析xml(查找带有特定文本的标签)
- javascript - 从s3获取后如何在浏览器中播放视频文件?
- triggers - H2 - 无法在“插入后”触发器中写入数据库
- android - 使用 Firebase 函数将实时数据库中的数据发送到电子邮件
- html - 表格单元格中同一行高的输入和符号彼此相邻?
- mysql - 而 mysql 可以在 /var/lib 中创建具有 drwxr-xr-x 权限的目录?
- .net-core - 是否可以在 C++/CLI 项目中使用 dotnet core
- ubuntu - 将 VPS 上的 nginx 从 http 转换为 https