在mongodb中插入新字段会删除其他集合属性

时间:2015-03-25 03:48:16

标签: mongodb

当我在我的users集合中插入一个新字段时,有几个属性会消失。最初,我的收藏品看起来像这样:

{
"_id": "myfi3E4YTf9z6tdgS",
"createdAt": ISODate("2015-03-20T16:25:06.978Z"),
"emails": {
    "address": "abc123@gmail.com",
    "verified": true
},
"profile": {
    "companyName": "Company1",
    "markup": "5",
    "phoneNum": "555-555-5555"
},
"services": {
    "password": {
        "bcrypt": "$2a$10$EsecJJz.PA/qgupHzknYBuGQRW4c6S9hFScc4GesOcO7pixOna1AG"
    },
    "resume": {
        "loginTokens": [
            {
                "when": ISODate("2015-03-23T20:58:48.642Z"),
                "hashedToken": "dlPlzU7KtVhMW1JPDgCQWPYgqIc825ao2bnR84q9NQI="
            }
        ]
    }
},
}

然后我在终端中输入以下命令添加了一个admin标志字段:

db.users.update({_id: 'myfi3E4YTf9z6tdgS'}, {$set: {profile{ admin: true}}

我再次检查了集合的属性并找到了:

{
"_id": "myfi3E4YTf9z6tdgS",
"createdAt": ISODate("2015-03-20T16:25:06.978Z"),
"emails": {
    "address": "abc123@gmail.com",
    "verified": true
},
"profile": {
    "admin": true
},
"services": {
    "password": {
        "bcrypt": "$2a$10$EsecJJz.PA/qgupHzknYBuGQRW4c6S9hFScc4GesOcO7pixOna1AG"
    },
    "resume": {
        "loginTokens": [
            {
                "when": ISODate("2015-03-23T20:58:48.642Z"),
                "hashedToken": "dlPlzU7KtVhMW1JPDgCQWPYgqIc825ao2bnR84q9NQI="
            },
            {
                "when": ISODate("2015-03-25T03:32:37.172Z"),
                "hashedToken": "xrojAUw7VwQvbjMtDwaexFEtQprMgl85b+0SY18z58c="
            }
        ]
    }
},
}

profile.companyName,profile.markup和profile.phoneNum消失了。有谁知道发生了什么?请帮忙!

2 个答案:

答案 0 :(得分:2)

使用点表示法更新嵌入对象(如profile)中的单个字段,而不是替换整个嵌入对象:

db.users.update({_id: 'myfi3E4YTf9z6tdgS'}, {$set: {'profile.admin': true}})

答案 1 :(得分:0)

为什么不使用db.users.save()函数 语法可能看起来像

db.users.save({_id: 'myfi3E4YTf9z6tdgS', 'profile.admin': true})