mongoDB-获取子字符串&;在分组阶段将字符串转换为数字
我试图通过MongoDB中的聚合计算员工的工资总额,问题是工资以货币符号<代码>$为准,无法在组中获得总额 示例数据库条目:mongoDB-获取子字符串&;在分组阶段将字符串转换为数字,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我试图通过MongoDB中的聚合计算员工的工资总额,问题是工资以货币符号$为准,无法在组中获得总额 示例数据库条目: { "_id" : ObjectId("5e2f408b1548343a74dce68a"), "employee_first_name" : "Gwenaëlle", "employee_last_name" : "Shawley", "department" : "Product Management", "salary" : "$205223.43",
{
"_id" : ObjectId("5e2f408b1548343a74dce68a"),
"employee_first_name" : "Gwenaëlle",
"employee_last_name" : "Shawley",
"department" : "Product Management",
"salary" : "$205223.43",
"years_in_job" : 17,
"dob" : "4/12/1980",
"childrenId" : [
ObjectId("5e2da031c71c0b0f54e35236"),
ObjectId("5e2da031c71c0b0f54e35234"),
ObjectId("5e2da031c71c0b0f54e35235"),
],
"updatedAt" : ISODate("2020-02-06T16:47:29.208Z")
}
用MongoDB编写的查询:
aggregation query:
db.getCollection('employee_details')
.aggregate([
{ $match: { department: "Product Management" } },
{
$group:
{
"_id": "$years_in_job",
total: { $sum: '$salary' }
}
}
])
我建议您先删除工资中的$,然后在计算完总值后对其进行预处理或连接。我建议您先删除工资中的$,然后在计算完总值后对其进行预处理或连接。尝试此查询:
db.getCollection('employee_details')
.aggregate([
{ $match: { department: "Product Management" } },
{
$group:
{
"_id": "$years_in_job",
/** get substring of salary which removes $ from string & then convert it into double for sum */
total: { $sum: { $toDouble: { $substr: ["$salary", 1, -1] } } }
}
}
])
测试:尝试以下查询:
db.getCollection('employee_details')
.aggregate([
{ $match: { department: "Product Management" } },
{
$group:
{
"_id": "$years_in_job",
/** get substring of salary which removes $ from string & then convert it into double for sum */
total: { $sum: { $toDouble: { $substr: ["$salary", 1, -1] } } }
}
}
])
测试:它工作正常还是仍然存在问题?如果确实如此,请接受这一点&您的问题将以一个有效的答案结束:-)它是否有效或仍然存在问题?如果确实如此,请接受这一点&您的问题将以有效答案结束:-)