Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find and Update nested array element by ID

I have a user model something like this

{
     _id:"something",
     email:"abc@gmail.com",
     contacts:[
     {_id:"123",status:"PENDING"},
     {_id:"456",status:"PENDING"},
     {_id:"789",status:"PENDING"}
     ]
}

And I have an id of one of the user’s contacts "123" and I want to update that specific contact’s status from "PENDING" to "SUCCESSFUL". How can I do that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Easiest way is with the array identifier $, like so:

db.collection.updateOne({
  email: "abc@gmail.com",
  "contacts._id": "123"
},
{
  "$set": {
    "contacts.$.status": "SUCCESSFUL"
  }
})

Mongo Playground

The array identifier updates the first element of the array that matches the query.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading