Rahul Sharma

Rahul Sharma

  • 1.7k
  • 284
  • 71.4k

Summation of sub document field based on a group unexpected

Jun 17 2016 8:09 AM
I have a document structured as
{
"_id" : ObjectId("5763d4a54da83b98f269878a"),
"Company_id" : "INTG",
"First_Name" : "fgfg",
"Last_Name" : "Sharma",
"Emp_Id" : "301",
"Department" : "QA",
"Emp_Status" : "Active",
"Salary" : {
"HRA" : "1200",
"Basic" : "1000",
"Home_Allowance" : "100",
"Other_Allowance" : "400"
}
}
{
"_id" : ObjectId("5763d4b94da83b98f269878b"),
"Company_id" : "INTG",
"First_Name" : "reena",
"Last_Name" : "Sharma",
"Emp_Id" : "301",
"Department" : "QA",
"Emp_Status" : "Active",
"Salary" : {
"HRA" : "200",
"Basic" : "1000",
"Home_Allowance" : "100",
"Other_Allowance" : "100"
}
}
And i want to get sum of basic salary based on department Like
**Expected output**
**Department Total_Basic**
QA 2000
I have used the following code to get the output
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
I think $unwind is not Working..Please suggest