如何在MongoDB关联Employee与Salary集合查询薪资最高/最低员工?
查询薪资最高与最低的员工(Node.js + Mongoose实现)
你可以通过Mongoose的聚合框架,关联Employee和Salary集合来实现需求。以下是两种可行的实现方式:
方式一:分别查询最高/最低薪资员工
通过聚合关联两个集合后,按薪资排序并取首尾数据:
// 查询薪资最高的员工 const highestPaidEmployee = await Employee.aggregate([ { $lookup: { from: 'salaries', // 替换为你的Salary集合实际名称(Mongoose默认模型名转复数) localField: 'id', foreignField: 'id', as: 'salaryInfo' } }, { $unwind: '$salaryInfo' }, // 展开薪资关联结果数组 { $sort: { 'salaryInfo.amount': -1 } }, // 按薪资降序排序 { $limit: 1 }, // 取第一条(薪资最高的员工) { $project: { // 构造返回的字段结构 _id: 0, id: '$id', name: '$name', highestSalary: '$salaryInfo.amount' } } ]); // 查询薪资最低的员工 const lowestPaidEmployee = await Employee.aggregate([ { $lookup: { from: 'salaries', localField: 'id', foreignField: 'id', as: 'salaryInfo' } }, { $unwind: '$salaryInfo' }, { $sort: { 'salaryInfo.amount': 1 } }, // 按薪资升序排序 { $limit: 1 }, // 取第一条(薪资最低的员工) { $project: { _id: 0, id: '$id', name: '$name', lowestSalary: '$salaryInfo.amount' } } ]); console.log('薪资最高员工:', highestPaidEmployee[0]); console.log('薪资最低员工:', lowestPaidEmployee[0]);
方式二:一次聚合获取两者
通过分组操作同时获取最高和最低薪资的员工,减少数据库查询次数:
const salaryExtremes = await Employee.aggregate([ { $lookup: { from: 'salaries', localField: 'id', foreignField: 'id', as: 'salaryInfo' } }, { $unwind: '$salaryInfo' }, { $sort: { 'salaryInfo.amount': -1 } }, // 降序排序后,第一条是最高,最后一条是最低 { $group: { _id: null, highestPaid: { $first: '$$ROOT' }, lowestPaid: { $last: '$$ROOT' } } }, { $project: { _id: 0, highestPaid: { id: '$highestPaid.id', name: '$highestPaid.name', salary: '$highestPaid.salaryInfo.amount' }, lowestPaid: { id: '$lowestPaid.id', name: '$lowestPaid.name', salary: '$lowestPaid.salaryInfo.amount' } } } ]); console.log('薪资极值员工:', salaryExtremes[0]);
注意事项
- 确保
from字段的值是你的Salary集合实际名称,Mongoose默认会将模型名转为复数形式(比如Salary模型对应salaries集合),如果自定义了集合名请替换。 - 你的集合使用自定义
id字段而非Mongoose默认的_id,所以聚合中关联的字段要保持一致。
内容的提问来源于stack exchange,提问作者Manas S. Roy
相关产品推荐
相关产品推荐

