MST

星途 面试题库

面试题:MongoDB Shell中嵌套复杂对象变量的编辑与查询

在MongoDB Shell中,有一个集合data,文档结构如下:{ '_id': ObjectId('...'), 'complexObj': { 'nestedObj': { 'list': [ { 'key1': 'value1', 'key2': 10 }, { 'key1': 'value2', 'key2': 20 } ] } } } 。请编写代码,将list数组中key2大于15的对象的key1值改为大写,并且查询修改后的文档。
15.5万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
// 使用updateMany方法更新符合条件的文档
db.data.updateMany(
    { "complexObj.nestedObj.list.key2": { $gt: 15 } },
    [
        {
            $addFields: {
                "complexObj.nestedObj.list": {
                    $map: {
                        input: "$complexObj.nestedObj.list",
                        as: "item",
                        in: {
                            $cond: [
                                { $gt: ["$$item.key2", 15] },
                                { key1: { $toUpper: "$$item.key1" }, key2: "$$item.key2" },
                                "$$item"
                            ]
                        }
                    }
                }
            }
        }
    ]
);

// 查询修改后的文档
db.data.find();