Upsert Array Elements matching criteria in a MongoDB document

questionsCategory: QuestionsUpsert Array Elements matching criteria in a MongoDB document
Dilip asked 2 years ago

Hi,
I want to upsert the array elements, so if one doesnt match then insert it, otherwise update it.
I tried the answer on that question, and it works fine IF the array element already exists. If the element doesnt exist then it creates a child of “$” under the array field.
My Mongo structure is as follows:

Widget (collection)
--Name
--Properties (array)
  --Name
  --Value

My application gets a Widget Name and a list of Properties from a WebService call. I wish to iterate the provided Properties and update the value in the MongoDB if the Name already exists, OR insert a new Property to the Properties array if it doesnt.