*I have a document structured in which we embedded the salary Document into the Employee_Detail Document.As per the MongoDb documantation ,we can use $Unwind to deconstruct the Document and use aggregated pipeline...But its not working. i am using the below script...*
{
"_id" : ObjectId("5763d4a54da83b98f269878a"),
"First_Name" : "fgfg",
"Department" : "QA",
"Salary" : {
"HRA" : "1200",
"Basic" : "2000",
}
})
And i want to get sum of basic salary based on department Like
然后预期的输出是 部门Total_Basic ** QA 2000
I have used the following code to get the output. I have used the $unwind to deconstruct the document.and use aggregated pipeline to group the department(Sum of basic Salary).
db.Employee_Detail.aggregate([
{$unwind:"$Salary"}, {$group: {"_id": "$Department", total_Basic: {$sum: "$Salary.Basic" }
}}
])
But i get the below Result.
Department Total_Basic
QA 0
我认为$ unwind不起作用。请建议
答案 0 :(得分:0)
您的主要问题是字段的类型Basic
是一个字符串。其次,除非字段Salary
包含数组,否则不需要使用unwind。
因此,请执行更新以将Basic
和HRA
的类型转换为浮点数,(see this stackoverflow question)
然后像这样的聚合操作会给你想要的结果:
db.Employee_Detail.aggregate([
{$group: {"_id": "$Department", total_Basic: {$sum: "$Salary.Basic" }}
])