Django+MongoEngine – How to Perform an Update_or_Create Action

BuiltIn ORM

Django provides a convenient method when needing to update a model instance, but create if it does not exist. The method is shown below,

update_or_create(defaults=None, **kwargs)

However MongoEngine replaces the builtin object-relational mapper (ORM). Because of this an alternative is required.

MongoEngine

Within MongoEngine the modify method can be used to achieve the same goal. Lets look at an example. First of all below is our example model,

class Fruit(mongoengine.Document): 
    number = mongoengine.StringField(max_length=50, unique=True) 
    color = mongoengine.StringField(max_length=50) 
    size = mongoengine.StringField(max_length=50)

And now lets look at the modify command.

Fruit.objects(number='12345').modify(upsert=True, new=True, 
                                     set__color='green',
                                     set__size='small')

The 2 main parameters are,

  • upsert – insert if document doesn’t exist
  • new – return updated rather than original document
Rick Donato

Want to become a Django expert?

Here is our hand-picked selection of the best courses you can find online:
The Complete Web Development Bootcamp course
Django Practical Guide course
Django Full Stack Developer Bootcamp
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial