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.
2
  • Have you tried using findAndUpdateOne()? Commented Nov 13, 2017 at 13:23
  • @JohnKennedy How can I access to nested object from findOneAndUpdate? I don't know how to... Commented Nov 13, 2017 at 13:27

1 Answer 1

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){

         });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works,! I should have used some specific key for this. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.