简体   繁体   中英

How to add new attribute to array of nested sub document in MongoDB

{
    "_id" : ObjectId("559f85351554febf038b5c70"),
    "company_name" : "Honey Crunch Popcorn Co",
    "tech" : [
        {
            "tech_name" : "Magento",
            "user" : "Rahul",
        },
        {
            "tech_name" : "Volusion",
            "user" : "Tina",
        }
    ]
}

I want to add new attribute "verified:true" to "tech" array for "tech_name" : "Volusion" only so it will result like this,

{
    "_id" : ObjectId("559f85351554febf038b5c70"),
    "company_name" : "Honey Crunch Popcorn Co",
    "tech" : [
        {
            "tech_name" : "Magento",
              "user" : "Rahul"
        },
        {
            "tech_name" : "Volusion",
            "user" : "Tina",
            "verified" : "true"
        }
    ]
}

Please Help.

To do this you use the $set operator in an update statement, whilst referencing the matched array element via the positional $ operator :

db.collection.update(
    {
        "_id": ObjectId("559f85351554febf038b5c70"),
        "tech.tech_name": "Volution"
    },
    {
        "$set": {
            "tech.$.verified": true
        }
    }
)

So what that does is:

  1. The "query" or first argument portion of the .update() both finds a unique document ( not really required ) by field reference and secondly finds a field in the nested array my it's own matching "field/property". This last part is important for the next stage.

  2. The "update" portion of the .update() method here as the "second" argument contains the definition for "what gets modified". Using the $set operator here makes sure that only the referenced fields get modified in any way.

    Then the "positional" $ operator here makes sure that only the "matched index" of that array element referenced from the query portion is the element that gets updated. This uses the "dot notation" form of

     $set: { "tech.$.verified": true } 

    That references the "correct" indexed field in the element and "creates" a new property where one does not already exist or otherwise "overwrites" an existing value.

Those are the basics of how this works. The primary things to take away from here are:

  1. Match an indexed value of an element in an array you wish to update and reference it via "dot notation".

  2. Use the $set operation or other appropriate "update operator" for the field rather than providing a "raw" object structure in the "update" that would otherwise "overwrite" the existing object.

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