MongoEngine: Replacing get_or_create with upsert/update_one

django, mongoengine

Solution

You are very close but you need to use a findAndModify command via modify rather than an update command.

NewDoc = Model.objects(first_name='John', 
                       last_name='Potter', 
                       age=40).modify(upsert=True, new=True,
                                      set__first_name='John, 
                                      set__last_name='Potter', 
                                      set__age=40,
                                      set_on_insert__newUser=True)

Take note of the first 2 modify kwargs - `upsert` and `new`. Also take note of the $setOnInsert operator example which will only set a field if the findAndModify does an upsert.

Problem

I understand that `get_or_create` is now deprecated in favour of using `upsert`, but how do I make `update_one` to return the object rather the number of objects modified, and can I just retrieve an object if I don't want to update anything? e.g. ``` Model.objects.get_or_create(first_name='John', last_name='Potter', age=40) # assuming that first_name + last_name + age are enough to uniquiely indentify a person ``` returns a Model object (a new object if it didn't exist, and existing object if it does). What would be the equivalent of this using the new method? ``` Model.objects(first_name='John', last_name='Potter', age=40).update_one(upsert=True) # returns number of objects (1) Model.objects(first_name='John', last_name='Potter', age=40).update_one(set__first_name='John', set__last_name='Potter', set__age=40,upsert=True) # returns number of objects (1) ``` Is there a way to make it return the object, and make it behave exactly like `get_or_create`? I couldn't find how to do this in the documentation

Original source

Related problems