MST

星途 面试题库

面试题:MongoDB Shell中复杂数组变量的编辑

假设在MongoDB Shell中有一个集合documents,其中的文档包含一个数组字段arrayField,数组中每个元素是一个对象,对象有name和value两个属性。现在要将arrayField中所有name为'target'的元素的value值翻倍,用MongoDB Shell代码实现。
46.4万 热度难度
数据库MongoDB

知识考点

AI 面试

面试题答案

一键面试
db.documents.updateMany(
    {},
    [
        {
            $set: {
                arrayField: {
                    $map: {
                        input: "$arrayField",
                        in: {
                            $cond: [
                                { $eq: ["$$this.name", "target"] },
                                { name: "$$this.name", value: { $multiply: ["$$this.value", 2] } },
                                "$$this"
                            ]
                        }
                    }
                }
            }
        }
    ]
);