简体   繁体   English

对象内部的JSON更新数组

[英]JSON update array inside of object

Here's what my JSON response looks like: 我的JSON响应如下所示:

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

I'm trying to update the score array inside one of the objects, here's my attempt at it: 我正在尝试更新其中一个对象内的得分数组,这是我的尝试:

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

Try the following update: 尝试以下更新:

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

which uses the dot notation to access the elements of an array and to access the fields of an embedded document. 它使用点表示法访问数组的元素并访问嵌入式文档的字段。

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>'

I think you are looking for 我想你在找

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

A better way to do it is to not reply on the index of the quizzes array and use the "wk" attribute 一种更好的方法是不对测验数组的索引进行答复,而使用“ wk”属性

db.collection('connect').update({_id: id,quizzes:{$elemMatch:{"wk":1}}}, {$set: { quizzes.$.score: 89  }  }})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM