如何在MongoDB(NOSQL)中添加新字段



我是NOSQL数据库的新手,并使用Mongo版本2.4.12。我的集合称为"用户",我想添加名为"用户邮件"的新字段。您能否让我知道如何从命令行/壳终端进行操作?

> db.user.find({username :"John"}).pretty();
{
        "_id" : "ajd233d-u980-4000-92b6-5353e9602502",
        "username" : "John",
        "password" : "John",
        "firstname" :"John",
        "lastname" : "Rogers",
        "enabled" : true,
        "employeeauth" : [
                {
                        "employeeId" : "a2fg190-b50d-14k2-aan0-ebb7298fa2b7",
                        "authorities" : [
                                "DEVELOPER", "TESTER", "CONSULTANT"
                        ]
                }
        ],
}

我想添加新的字段"用户邮件",因此结果表演如下:

> db.user.find({username :"John"}).pretty();
    {
            "_id" : "ajd233d-u980-4000-92b6-5353e9602502",
            "username" : "John",
            "password" : "John",
            "firstname" :"John",
            "lastname" : "Rogers",
            "useremail": "john.rogers@test.com",
            "enabled" : true,
            "employeeauth" : [
                    {
                            "employeeId" : "a2fg190-b50d-14k2-aan0-ebb7298fa2b7",
                            "authorities" : [
                                    "DEVELOPER", "TESTER", "CONSULTANT"
                            ]
                    }
            ],
    }

在这里您去db.user.update({username:"John"},{$set:{"useremail":"john.rogers@test.com"}})

{username:"John"}是查询, {"useremail":"john.rogers@test.com"}是更新。

如果文档中不存在字段useremail,则将插入。如果已经存在,则将更换该值。

参考

最新更新