MST
星途 面试题库

面试题:MongoDB find命令的复杂条件组合与排序

在一个名为‘employees’的集合中,文档结构为{‘name’:‘string’, ‘department’:‘string’, ‘salary’:‘number’, ‘join_date’:‘date’}。要求使用find命令查询出在‘研发部’或‘市场部’,且薪资高于平均薪资的员工,并按入职时间从早到晚排序,最后返回员工姓名、部门和薪资。请写出具体命令及实现思路。
50.2万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 首先计算employees集合中所有员工的平均薪资。
  2. 使用find命令筛选出部门为‘研发部’或‘市场部’,且薪资高于平均薪资的员工。
  3. 对筛选出的员工按join_date从早到晚排序。
  4. 仅返回员工的姓名、部门和薪资。

具体命令

假设使用的是 MongoDB,命令如下:

// 计算平均薪资
const averageSalary = db.employees.aggregate([
    { $group: { _id: null, avgSalary: { $avg: "$salary" } } }
]).toArray()[0].avgSalary;

// 查询符合条件的员工
db.employees.find({
    $and: [
        { department: { $in: ['研发部', '市场部'] } },
        { salary: { $gt: averageSalary } }
    ]
}, { name: 1, department: 1, salary: 1, _id: 0 })
.sort({ join_date: 1 });

在上述代码中,先通过aggregate方法计算平均薪资,然后在find方法中使用$and操作符来满足部门和薪资的条件,投影中指定只返回namedepartmentsalary字段,最后通过sort方法按join_date升序排序。