2
{ 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?

insearchof
  • 49
  • 1

3 Answers3

2

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.

Muirik
  • 6,049
  • 7
  • 58
  • 116
  • 1
    thanks! i was looking at $match in mongodb documentation too, and tested it, yup, that's the correct method! thanks. – insearchof Jul 17 '20 at 02:31
1

You need to use $match.

db.emp.aggregate([
    { $match: { department: "IT" } },
    { $group: { _id: "$department", maxSalary: { $max: "$salary" } } }
]);
Ahmed ElMetwally
  • 2,276
  • 3
  • 10
  • 15
0
    db.emp.aggregate([
  { $group:
    { _id: "$department",
      maxSalary: { $max: "$salary" }
    }
  },
{ $match :{_id: 'IT'} } ])
Neha Sinha
  • 173
  • 1
  • 6