简体   繁体   中英

JSON update array inside of object

Here's what my JSON response looks like:

"_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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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