如何做“插入如果不存在其他更新”用mongoengine? [英] How to do "insert if not exist else update" with mongoengine?
问题描述
这是我的文件定位:
class位置(mongoengine.Document):
user_id = mongoengine.IntField(required = True)
point = mongoengine.GeoPointField(required = True)
我想这样做:
给定一个 user_id
和一个点
:
如果没有这个 user_id
的文档,请使用 user_id
和 point
并保存;
否则用 user_id
。
我可以在一个使用mongoengine的语句中执行此操作吗?
请注意, get_or_create
现在被安排为不推荐使用,因为MongoDB中没有事务支持,因此无法保证原子性。
首选方式是更新与upsert:
Location.objects(user_id = user_id)。 update_one(set__point = point,upsert = True)
更多关于 MongoDB文档。
I'm working with mongoengine in Django,
this is my document defination:
class Location(mongoengine.Document):
user_id = mongoengine.IntField(required=True)
point = mongoengine.GeoPointField(required=True)
I want to do this:
given a user_id
and a point
:
if there is no document that have this user_id
, create one with the user_id
and point
and save it;
else update the document with user_id
with point
.
Can I do this in one statement 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.
这篇关于如何做“插入如果不存在其他更新”用mongoengine?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!