2

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?

Saadi
  • 121
  • 1
  • 8

2 Answers2

2

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.

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
0
db.collection.updateOne({ _id: "something" }, { contacts: [{ _id: "123", status: "SUCCESSFUL" }] }, function (err, res) {
    
})
tripleee
  • 175,061
  • 34
  • 275
  • 318
Harsh Gupta
  • 548
  • 1
  • 4
  • 10