MongoDB Find max salary of a department

Viewed 118
{ id: '101', name: 'Ethan', department: 'IT', salary: 5000 },
{ id: '102', name: 'Sally', department: 'Sales', salary: 6000 },
{ id: '103', name: 'Harry', department: 'HR', salary: 4000 },
{ id: '104', name: 'Jane', department: 'HR', salary: 3500 },
{ id: '105', name: 'Adam', department: 'IT', salary: 6000 },
{ id: '106', name: 'Henry', department: 'IT', salary: 8000 },
{ id: '107', name: 'Dianne', department: 'Sales', salary: 8000 },
{ id: '108', name: 'Barbie', department: 'Sales', salary: 7000 }

is there a way to find the max salary of a department? say IT

db.emp.aggregate([
  { $group:
    { _id: "$department",
      maxSalary: { $max: "$salary" }
    }
  }
])

this returns all departments but is there a way to only get for say IT department within the same aggregate statement?

3 Answers

You can add $match to your aggregate statement. It works like this:

db.articles.aggregate( [
  { $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },
  { $group: { _id: null, count: { $sum: 1 } } }
] );

In your case you'd $match on a particular department.

To be clear, this operation first selects documents to process using the $match pipeline operator, and then pipes the results to the $group pipeline operator.

You need to use $match.

db.emp.aggregate([
    { $match: { department: "IT" } },
    { $group: { _id: "$department", maxSalary: { $max: "$salary" } } }
]);
    db.emp.aggregate([
  { $group:
    { _id: "$department",
      maxSalary: { $max: "$salary" }
    }
  },
{ $match :{_id: 'IT'} } ])
Related