简体   繁体   中英

How to update a specified field having a given value in mongo db

Here i want to update a given document as below

{
    
    "emailid": "xxx.gmail",
    
    "user_devices": [],
    "devices": [{
        "created_time": 1607153351,
        "token": 123
    },
    {
        "created_time": 1807153371,
        "token": 1345
    }]
}

here i need to update field devices with the token of 1345 with a new field like "Newfield":"newfield" where the final output would look like as below

{
    
    "emailid": "xxx.gmail",
    
    "user_devices": [],
    "devices": [{
        "created_time": 1607153351,
        "token": 123
    },
    {
        "created_time": 1807153371,
        "token": 1345,
        "Newfield":"newfield"

    }]
}

How to update the mongo db like this. Thanks in advance for your answers.

db.products.update({
  "devices.token": 1345 //Matching condition
},
{
  $set: {
    "devices.$.t": 2 //Updates the matched element in the array
  }
})

you can do it using positional operator - Reference

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