【问题标题】:How to add new field to collection in MongoDB (NoSQL)如何在 MongoDB (NoSQL) 中向集合中添加新字段
【发布时间】:2015-05-06 05:15:45
【问题描述】:

我是 NoSQL 数据库的新手,使用的是 Mongo 2.4.12 版。我有一个名为“user”的集合,我想添加一个名为“useremail”的新字段。能否请您告诉我如何从命令行/shell 终端执行此操作?

> 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"
                        ]
                }
        ],
}

我想添加新字段“useremail”,所以结果显示如下:

> 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"
                            ]
                    }
            ],
    }

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    给你db.user.update({username:"John"},{$set:{"useremail":"john.rogers@test.com"}})

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

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

    reference

    【讨论】:

    • 嗨 - 它似乎没有按预期工作,它覆盖了我所有的日期并给出:>db.user.update({username:"John"},{"useremail":"john.rogers@ test.com"}) > db.user.find({username :"John"}).pretty(); { "_id" : ObjectId("54fcbae626f96d47769f86bb"), "useremail" : "john.rogers@test.com" }
    • @user4567570 请参阅编辑。使用{$set:{"useremail":"john.rogers@test.com"}} 进行文档更新
    • 是的,现在工作了。谢谢你。这是mongo的美丽。只是我需要为以前的错误文档更新查询取回所有数据。
    猜你喜欢
    • 2011-12-04
    • 2020-09-22
    • 2019-09-29
    • 2021-06-04
    • 2015-09-06
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多