As per How do I update Array Elements matching criteria in a MongoDB document?
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.
What you require is not possible using a single update without some app-side logic. Note that upsert as a feature is not relevant for this specific problem unless you want to automatically create new Widget documents if none exist with the provided name.
The problem you're running into is that there is no functionality that allows you to do two different updates depending on the existence of an array element. Your only two options are :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With