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.
解决方案
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);
}
});