How to push json to an array in mongodb

I want to add json in this format, what am I doing for this

student{
      nmae:testing
    marks:[{
            subject:{
                class1:2,
                name:testing,
                number:56,
                grade:b,
            },
    {
            subject:{
                class1:2,
                name:testg,
                number:54,
                grade:b,
            }
        }],
}

I used

db.students.update({"name":"testing"},{$push:{"marks":{"subject":{"class1":1,name:"math","number":12,"garde":"B"}}}});

but this is not a job or a mistake. I do not know where I am wrong, help me

+4
source share
1 answer

As you can see in the resulting document, you have an object as the value of the fields marks:

{
    "_id" : ObjectId("55b38136c645304214249b68"), 
    "name" : "testing", 
    "rollnumber" : "12345", 
    "password" : "testing", 
    "issuebook" : [], 
    "marks" : {
        "subject" : {
            "class1" : 1, 
            "name" : "math", 
            "number" : 12, 
            "garde" : "B"
        } 
    }, 
    "__v" : 0, 
    "status" : "Active", 
    "status1" : "Active"
}

So you get an error.

Follow these steps to restore:

db.student.remove({_id: ObjectId("55b38136c645304214249b68")})
db.student.insert({
        "_id" : ObjectId("55b38136c645304214249b68"), 
        "name" : "testing", 
        "rollnumber" : "12345", 
        "password" : "testing", 
        "issuebook" : [], 
        "marks" : [
            {
                "subject" : {
                    "class1" : 1, 
                    "name" : "math", 
                    "number" : 12, 
                    "garde" : "B"
                }
            }
        ] 
        "__v" : 0, 
        "status" : "Active", 
        "status1" : "Active"
    }
)
+2
source

Source: https://habr.com/ru/post/1599647/


All Articles