Search code examples
mongodbmongodb-queryinsert-update

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.


Solution

  • 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