How to change a field & add a sub-field in Mongodb

房东的猫 提交于 2020-01-26 03:15:38

问题


I have mongo documents like the following:

{
    "_id" : ObjectId("591e36eb2cdce09936d8e511"),
    "bday" : null,    
    "studentId" : "000004"

}

I want to make it :

{
    "_id" : ObjectId("591e36eb2cdce09936d8e511"),
    "bday" : null,    
    "studentId" : {
        "id" : "000004"
    }    
}

I have tried the following:

db.persons.update({"studentId": "000004"},{$set : {"studentId.id": "000004"}},false,true)

But it is giving an error:

LEFT_SUBFIELD only supports Object: studentId not: 2

Can anyone help?

Thanks,
Sumit.


回答1:


In your case you see an error because you are trying to take "studentId" which is string and add a property inside it. To fix it you should set entire new object like this

db.persons.update({"studentId":"000004"},{$set:{"studentId":{"id":"000004"}}})

Another option, if, for example you need to change structure for entire collection, is to just iterate over each element and update them. Like this:

db.persons.find({}).forEach(function (item) {
    if (item.studentId != null){
        item.studentId = {id:item.studentId};
        db.persons.save(item);
    }
});



回答2:


I hope this will help

db.collection.update({_id:ObjectId("591e36eb2cdce09936d8e511")},{$set:{"studentId":{"id":"000004"}}})


来源:https://stackoverflow.com/questions/44069331/how-to-change-a-field-add-a-sub-field-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!