top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

MongoDB: How does aggregate function works ? Please explain through an example.

+3 votes
366 views
MongoDB: How does aggregate function works ? Please explain through an example.
posted Jul 5, 2015 by Vikram Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

When a possible group result is necessary then aggregation is used. I would like to explain aggregation by using an example as you asked.
Let us consider, a collection "employeeDB" holds employee's records/documents. Each record/document has fields likes name, designation, salary, gender, location etc.
Sample:
name: "abc", designation: "engineer", salary:30000, gender:"female", location: "Gurgaon"
name: "xyz", designation: "engineer", salary:40000, gender:"female", location: "Gurgoan"
name: "def", designation: "engineer", salary:40000, gender:"female", location: "Hyderabad"
name: "ghi", designation: "engineer", salary:45000, gender:"male", location: "Bangalore"
name: "jkl", designation: "engineer", salary:40000, gender:"male", location: "Chennai"
name: "mno", designation: "engineer", salary:40000, gender:"male", location: "Chennai"
... and so on.

Now if you want to know average salary of engineer per location then you have to use aggregate function on location field.
It will be like that.

db.employeeDB.aggregate({ $group : { _id: "$location", averageSalary : {$avg : "$salary"} } })
answer Jul 5, 2015 by Neelam
...