Ajmal Razeel
Ajmal Razeel

Reputation: 1701

How to use $add aggregate in Mongodb?

I have a collection that stores employees data. This is the document structure for the collection 'employees'.

{
    "emp_id" : 3,
    "Employee_Name" : "Farquleet Shadab",
    "Employee_Gender" : "Male",
    "Employee_Salary" : [
        {
            "month_year" : "Jan-2015",
            "salary_paid" : 100

        },
        {
            "month_year" : "Feb-2015",
            "salary_paid" : 100
        }
    ]
},

{
    "emp_id" : 4,
    "Employee_Name" : "John Robert",
    "Employee_Gender" : "Male",
    "Employee_Salary" : [
        {
            "month_year" : "Jan-2015",
            "salary_paid" : 200

        },
        {
            "month_year" : "Feb-2015",
            "salary_paid" : 200
        }
    ]
}

Now I want to write to write a query to find the total salary paid to employees in the month_year = 'Jan-2015'. I am new to Mongodb and have no idea how to write query.

Upvotes: 1

Views: 169

Answers (2)

sergiuz
sergiuz

Reputation: 5539

You can try:

db.collection.aggregate([
    {$unwind: "$Employee_Salary"},
    {$match: {"Employee_Salary.month_year": "Jan-2015" }},
    {$project: {salary_paid: "$Employee_Salary.salary_paid"}},
    {$group: {_id: null, total_salary_paied_on_jan_2015: {$sum: "$salary_paid"}}}
])

this aggregation query will compute total amount of salary paid in Jan 2015 to all employees.

Upvotes: 1

Constantin Guay
Constantin Guay

Reputation: 1664

Here is an aggregation example:

db.salary.aggregate([
    {
        $unwind: "$Employee_Salary"
    }
    ,{
        $match:
        {
            "Employee_Salary.month_year" : "Jan-2015"
        }
    }
    ,{
        $group:
        {
            _id:null,
            total: { $sum: "$Employee_Salary.salary_paid" }
        }
    }
])

$unwind will explode your array, creating distinct documents for each. Then, $match will keep only the matching months. Finally, $group will add all salary from the docs that left.

Note: _id is not necessary, but if you want to know per example how much was salary per month, you'd just have to remove the $match doc, and into $group set _id: "$Employee_Salary.month_year".

Upvotes: 2

Related Questions