如何使用mongo shell更新Mongodb中数组的元素

时间:2018-04-07 22:24:34

标签: mongodb

我有以下文件

    { "_id" : ObjectId("5ac94112d99fefa76215853a"),
     "id" : "4969c4b2-afbf-4fba-bbb3-95a6899b446d", 
    "profiles" : [ { "loginInfo" : { "providerID" : "credentials",
     "providerKey" : "mc1@mc.com" }, "confirmed" : false,
     "email" : "mc1@mc.com", "firstName" : "m1", 
    "lastName" : "c1", "fullName" : "m1 c1", 
    "passwordInfo" : { "hasher" : "bcrypt", 
"password" : "$2a$10$5F62Gza9Z1ic7OabtXAQEeZhPqm7dfQfjlMMReI64cSZ8q0LJ3HQa" } } ]}

我想使用confirmed shell将字段false的值从true更改为mongo。我尝试了以下命令,但失败了。我做错了什么?

  

db.users.update({id:“4969c4b2-afbf-4fba-bbb3-95a6899b446d”},{$ set:{'profiles.confirmed':true}});

错误

WriteResult({
        "nMatched" : 0,
        "nUpserted" : 0,
        "nModified" : 0,
        "writeError" : {
                "code" : 16837,
                "errmsg" : "cannot use the part (profiles of profiles.confirmed) to traverse the element ({profiles: [ { loginInfo: { providerID: \"credentials\", providerKey: \"mc1@mc.com\" }, confirmed: false, email: \"mc1@mc.com\", firstName: \"m1\", lastName: \"c1\", fullName: \"m1 c1\", passwordInfo: { hasher: \"bcrypt\", password: \"$2a$10$5F62Gza9Z1ic7OabtXAQEeZhPqm7dfQfjlMMReI64cSZ8q0LJ3HQa\" } } ]})"
        }
})
>

1 个答案:

答案 0 :(得分:0)

db.users.update({
    id: "4969c4b2-afbf-4fba-bbb3-95a6899b446d",
    "profiles": {
        $elemMatch: {
            confirmed: false
        }
    }
}, {
    $set: {
        'profiles.$.confirmed': true
    }
});