javascript - JSON 更新对象内部的数组

标签 javascript json mongodb

这是我的 JSON 响应:

"_id" : 537,
    "quizzes" : [
        {
            "wk" : 1,
            "score" : [
                10
            ]
        },
        {
            "wk" : 2,
            "score" : [
                8
            ]
        },
        {
            "wk" : 3,
            "score" : [
                5
            ]
        },
        {
            "wk" : 4,
            "score" : [
                6
            ]
        }
    ]
}

我正在尝试更新其中一个对象内的分数数组,这是我的尝试:

db.collection('connect').update({_id: id}, {$push: { quizzes[0]: { score: 89  }  }});

最佳答案

尝试以下更新:

db.collection("connect").update(
    {
        "_id": id            
    }, 
    {
        "$set": { 
            "quizzes.0.score.0": 89    
        }
    }
);

它使用 dot notation 访问数组的元素以及访问嵌入文档的字段。

To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:

'<array>.<index>'

关于javascript - JSON 更新对象内部的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30959223/

相关文章:

javascript - 为什么在此示例中处理我的字符串时会得到额外的 ', '?

node.js - Mongodb的僧侣vs Mongoose

javascript - 如何推迟读取直到写入完成?

javascript - 如何在不丢失 javascript 结构的情况下过滤嵌套树对象?

node.js - Mongoose 聚合不返回最新文档

javascript - 为什么更新特定文件时 webpack --watch 不更新

javascript - Node - 如何将 MongoDB 时间戳转换为日期

javascript - 使用 Jquery 按钮无法禁用按钮

javascript - 用于检测不存在对象中的 JSON 属性的函数

java - @JsonPropertyOrder 和来自父类(super class)的字段