如何在Mongoose(MongoDB)中查询指定部门薪资最高的两名员工
问题原因
你遇到的populate is not a function报错有两个原因:
- Mongoose的
populate()方法仅适用于find()系列查询,aggregate()返回的聚合游标对象本身不支持populate方法 - 你的代码里写的是
populated,拼写也存在错误
实现方案
提供两种可直接使用的实现方式,都能输出你需要的返回格式:
方案1:find + populate 实现(逻辑更简单)
不需要使用聚合,直接用普通查询加关联查询,后续做简单格式化即可:
// 查询指定部门并关联员工信息,按薪资降序取前2位 const targetDept = await department.findOne({ name: 'abc' }).populate({ path: 'employee_id', options: { sort: { salary: -1 }, limit: 2 } }); // 整理为你需要的返回结构 const result = targetDept.employee_id.map(emp => ({ _id: emp._id, name: emp.name, salary: emp.salary, department: targetDept.name }));
方案2:纯aggregate聚合实现(性能更高,和SQL逻辑更接近)
用MongoDB原生的$lookup做关联,逻辑和MySQL的JOIN类似,适合熟悉SQL的开发者:
const result = await department.aggregate([ // 匹配指定名称的部门,对应SQL的WHERE { $match: { name: 'abc' } }, // 拆分员工id数组,每个id生成单独记录,对应SQL的拆行操作 { $unwind: '$employee_id' }, // 关联员工集合查询详情,对应SQL的LEFT JOIN { $lookup: { from: 'employees', // 这里填员工集合在MongoDB的真实名称,默认是model名小写加s,比如model叫employee则为employees localField: 'employee_id', foreignField: '_id', as: 'empInfo' } }, // 把关联返回的数组拆为单个对象 { $unwind: '$empInfo' }, // 按薪资降序排序,对应SQL的ORDER BY { $sort: { 'empInfo.salary': -1 } }, // 取前2条,对应SQL的LIMIT { $limit: 2 }, // 格式化输出字段为你需要的结构 { $project: { _id: '$empInfo._id', name: '$empInfo.name', salary: '$empInfo.salary', department: '$name' } } ]);
内容的提问来源于stack exchange,提问作者Sushant Rad
相关产品推荐
相关产品推荐

