Using mongodb, how would someone update a certain string inside an array?

Viewed 30

So, while building a webpage, I'd like to add a feature where you can change your password, email etc.. And I have all that info stored inside my database kinda like this:

// This is what it looks like in mongodb compass
Credentials: Array
0:
"email"
1:
"password"

how could I update 0 or 1?

1 Answers

You can use dot notation to set the postion you want in this way (assuming position 0 is always email and position 1 is always password):

db.collection.update({
  "user": "your_user_or_whatever_way_to_identify"
},
{
  "$set": {
    "credentials.0": "new email",
    "credentials.1": "new pass"
  }
})

Example here

Related