pythonmongodbmongoenginelistfield

How do I replace/update an element of mongoengine ListField of a collection in a MongoDB database? (in python)


I am just learning MongoDB queries and I have been trying to do the following for a few hours now: I have a class defined as

   class Uni(mongoengine.Document):
       instruments =mongoengine.ListField(mongoengine.ReferenceField(Instrument))

where Instrument is another Document object. Now I want to find a specific reference to Instrument object "old_instrument" in the ListField and replace the reference by a reference to "new_instrument". I have been trying the following:

Uni.objects(instruments=old_instrument).update(**{"set__$":new_instrument})

Can someone help me and elaborate the solution a little bit? Thank you very much!


Solution

  • so the solution I found is to read the array out from the database first, then modify it and update it back to the database. There seems to be no direct query solution.

        for u in Uni.objects(instruments=old_instrument):
            instr_array=u['instruments']
            instr_array=[new_instrument if x == old_instrument else x for x in instr_array]
            Uni.objects(name=u.name, date=u.date).update_one(upsert=True, instruments=instr_array)