Mongodb – Upsert Array Elements matching criteria in a MongoDB document

arraysmongodbupsert

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.

Best Answer

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 :

  1. Find the item, determine existence of relevant propertie(s), compile an appropriate update with your new or changes properties and execute it. This comes with the important downside that this is not a concurrency safe method. In other words, if two web services attempt this at the same one could overwrite eachother's changes.
  2. Make widget properties top level documents rather than embedded. Allows you to use upserts to do what you want. Obvious downside is that that isn't a very nice option in terms of schema design. You wouldn't automatically get all properties if you fetch a widget, for example.