简体   繁体   中英

How to update an already existing field in MongoDB

According to the MongoDB documentation, $set replaces the value of a field with the specified value or if it doesn't exist will add a new field with the specified value. My question is, how to add to an existing row without replacing an existing one, for example:

{
    "_id" : ObjectId("58dc9feca463e61042d2e462"),
    "email" : "spguillen@yahoo.com",
    "accountType" : "admin",
    "accessKeys" : [
        {
            "keyId" : "d06e6640-2f98-11e7-810b-67d01c2ba6eb",
            "name" : "Admin Key",
            "rights" : [
                "Read",
                "Create",
                "Delete"
            ]
        }
    ]
}

I want to add the following on the accessKeys field:

{"keyId": "50fcb190-5636-11e7-855a-0d21d5eb6743", "name": "Standard Key", "rights": ["Update"]}

Without the need to overwrite the existing access keys. Ideally also set a condition for any accounts where accountType: admin that if there are no accessKeys, it will set an accessKey field with the access key above yet when there is an access key, append the above access key to the existing one.

You can use $push operator which will append new item to an existing array. You can also use it for documents that don't have accessKeys field - in that case single element array will be created:

db.col.update(
    {"_id": ObjectId("58dc9feca463e61042d2e462")}, 
    { $push: { 
        "accessKeys": {"keyId": "50fcb190-5636-11e7-855a-0d21d5eb6743", "name": "Standard Key", "rights": ["Update"]} 
    } 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM