Update a document in a array by array inner document's id, but if that id's document does not exists in array create one with that Id in mongodb

I have a problem. I have a Document the structure is–

   _id : ObjectId("5da2de41a6889c3d9893270c"),
   marksAndMetas: [
   {st_id: 1, name: "x", mark: 23 },
   {st_id: 2, name: "y", mark: 25 }


I want to update a document in marksAndMetas array by st_id if document with same st_id exists. But if not exists I will push a document with that st_id into marksAndMetas

Hi @Md_Mahadia_86036,

I think what you are looking for is an upsert operation here. I would recommend you to watch the Lecture: Upserts again to get a better understanding.

In addition to this, please read the documentation on the update() function. This will help you in writing the desired query.

That being said, if you face any difficulty in understanding any of the concept or you are not able to write the query then please feel free to get back to us.

Hope it helps :slight_smile:

Shubham Ranjan
Curriculum Support Engineer