0

Let's suppose to there is db like below...

{ _id: 1234,
  key: 'Contacts',
  value: [
     { name: 'McDonald', phone: '1111'}, 
     { name: 'KFC', phone: '2222'}
  ]
}

And I want to change KFC's phone number to '3333'.

What I did is

DB.findOne({ key: 'Contacts' }, function(err, db){

        db.value[1]['phone'] = '3333'
        db.save(function(err, result){ 
            // done 
        })
    }
)

But it didn't update the database. What am I wrong?


  1. There's no specific _id in elements of array for some reason.
  2. Only the way to find specific element is index.
ton1
  • 7,238
  • 18
  • 71
  • 126

1 Answers1

2

Use the positional operator $

more info : https://docs.mongodb.com/manual/reference/operator/update/positional/#up.S

DB.update({key: "Contacts", "value.name": "KFC" },
         { $set: { "value.$.phone" : 666 } },function(err,doc){

         });
Arvind
  • 1,006
  • 10
  • 16