{ 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 }
有没有办法找到一个部门的最高工资?说IT
db.emp.aggregate([
{ $group:
{ _id: "$department",
maxSalary: { $max: "$salary" }
}
}
])
这会返回所有部门,但有没有办法在同一个聚合语句中仅获取 IT 部门?
最佳答案
您可以将 $match
添加到聚合语句中。它的工作原理如下:
db.articles.aggregate( [
{ $match: { $or: [ { score: { $gt: 70, $lt: 90 } }, { views: { $gte: 1000 } } ] } },
{ $group: { _id: null, count: { $sum: 1 } } }
] );
就您而言,您需要在特定部门
上$match
。
需要明确的是,此操作首先使用 $match
管道运算符选择要处理的文档,然后将结果通过管道传输到 $group
管道运算符。
关于MongoDB 查找一个部门的最高工资,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62946102/