如何将json推入mongodb中的数组

时间:2015-07-25 13:12:21

标签: mongodb

我想以这种格式添加json,我为此做了什么

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

我是用的

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

但它无法正常工作或出错。 我不知道我哪里错了请帮助我

1 个答案:

答案 0 :(得分:2)

正如您在结果文档中看到的那样,您有一个对象作为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"
}

所以你得到了错误。

执行以下操作以恢复:

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"
    }
)