MST

星途 面试题库

面试题:MongoDB中$project操作符与复杂表达式及条件判断的结合

假设有一个集合`employees`,文档结构如下:{"name":"Eve","department":"HR","salary":5000,"years_of_service":3}。使用聚合管道中的$project操作符,根据以下规则创建一个新字段`bonus`:如果员工在公司服务超过5年且所在部门是`Engineering`,则奖金为工资的20%;如果员工在公司服务超过3年且所在部门是`HR`,则奖金为工资的10%;其他情况奖金为0。最后只返回`name`和`bonus`字段,写出对应的聚合代码。
14.1万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
[
    {
        "$project": {
            "name": 1,
            "bonus": {
                "$cond": [
                    {
                        "$and": [
                            { "$gt": ["$years_of_service", 5] },
                            { "$eq": ["$department", "Engineering"] }
                        ]
                    },
                    { "$multiply": ["$salary", 0.2] },
                    {
                        "$cond": [
                            {
                                "$and": [
                                    { "$gt": ["$years_of_service", 3] },
                                    { "$eq": ["$department", "HR"] }
                                ]
                            },
                            { "$multiply": ["$salary", 0.1] },
                            0
                        ]
                    }
                ]
            }
        }
    }
]