How to do "insert if not exist else update" with mongoengine?
Note that get_or_create
is now scheduled to be deprecated, because with no transaction support in MongoDB it cannot ensure atomicity.
The preferred way is update with upsert:
Location.objects(user_id=user_id).update_one(set__point=point, upsert=True)
More on upserts on the MongoDB documentation.
There is a new way to do it since version 0.9 (explained here):
location = Location.objects(user_id=user_id).modify(upsert=True, new=True, set__point=point)
It returns the created or updated object.
this is what I came up with:
location = Location.objects.get_or_create(user_id=user_id)[0] location.point = point location.save()