如何更改字段在Mongodb中添加一个子字段 [英] How to change a field & add a sub-field in Mongodb

查看:944
本文介绍了如何更改字段在Mongodb中添加一个子字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下的mongo文档:

I have mongo documents like the following:

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

}

我想做到:

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

我尝试了以下操作:

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

任何人都可以帮忙吗?

谢谢,
Sumit.

Thanks,
Sumit.

推荐答案

在您的情况下,您看到一个错误,因为您试图获取字符串形式的"studentId"并在其中添加属性.要修复它,您应该像这样设置整个新对象

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

这篇关于如何更改字段在Mongodb中添加一个子字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆