Search code examples
pythonmongodbuniquemongoengine

ListField without duplicates in Python mongoengine


I must be missing something really obvious. But I can't seem to find a way to represent a set using mongoengine.

class Item(Document):
    name = StringField(required=True)
    description = StringField(max_length=50)
    parents = ListField(ReferenceField('self'))

i = Item.objects.get_or_create(name='test item')[0]

i2 = Item(name='parents1')
i2.save()
i3 = Item(name='parents3')
i3.save()
i.parents.append(i2)
i.parents.append(i2)
i.parents.append(i3)
i.save()

The above code will create a duplicate entry for i2 in the parents field of i1. How do you express a foreign key like relationship in mongoengine?


Solution

  • Instead of using append then using save and letting MongoEngine convert that to updates, you could use atomic updates and the $addToSet method - see the updating mongoDB docs

    So in your case you could do:

    i.update(add_to_set__parents=i2)
    i.update(add_to_set__parents=i3)
    i.update(add_to_set__parents=i2)
    

    Support for addToSet and each doesn't currently exist - see: https://github.com/MongoEngine/mongoengine/issues/33

    Update:

    add_to_set is supported.