【问题标题】:mongodb append to an existing objectmongodb 附加到现有对象
【发布时间】:2017-12-04 11:05:22
【问题描述】:

这是我的文档,我想在其中添加一个新字段:

{ 
email_address: 'webmaster@example.com', 
password: 'random_password',
first_name: 'John',
last_name: 'Doe',
website: {
    main_title: 'My Blog Website',
    main_url: 'http://www.example.com'
    }
}

目前我在做:

db.test.update({"email_address": "webmaster@example.com"},
{$set: {"website" : {"registrar": "namecheap"}}})

这会删除 website 中的其他字段,并添加这个新的 registrar 字段。我怎样才能附加到它?

【问题讨论】:

  • 我认为 $push 是你要找的东西

标签: arrays mongodb object mongodb-query


【解决方案1】:

您需要使用dot-notation 为子文档的特定字段设置值,而不是设置整个子文档:

db.test.update(
    { "email_address": "webmaster@example.com" },
    { $set: { "website.registrar" : "namecheap" } }
)

【讨论】:

    猜你喜欢
    • 2014-07-04
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 2010-10-11
    • 1970-01-01
    相关资源
    最近更新 更多