I'm working with mongoengine in Django,
this is my document defination:
我在Django中使用mongoengine,这是我的文档定义:
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?
我想这样做:给定一个user_id和一个点:如果没有这个user_id的文档,用user_id创建一个并指向并保存它;否则用user_id用point更新文档。我可以用mongoengine在一个声明中这样做吗?
3 个解决方案
#1
34
Note that get_or_create
is now scheduled to be deprecated, because with no transaction support in MongoDB it cannot ensure atomicity.
请注意,get_or_create现在计划不推荐使用,因为MongoDB中没有事务支持,因此无法确保原子性。
The preferred way is update with upsert:
首选方法是使用upsert进行更新:
Location.objects(user_id=user_id).update_one(set__point=point, upsert=True)
More on upserts on the MongoDB documentation.
有关MongoDB文档的upsert的更多信息。
#2
5
this is what I came up with:
这就是我提出的:
location = Location.objects.get_or_create(user_id=user_id)[0]
location.point = point
location.save()
#3
2
There is a new way to do it since version 0.9 (explained here):
从版本0.9开始,有一种新的方法(在此解释):
location = Location.objects(user_id=user_id).modify(upsert=True, new=True, set__point=point)
It returns the created or updated object.
它返回创建或更新的对象。
#1
34
Note that get_or_create
is now scheduled to be deprecated, because with no transaction support in MongoDB it cannot ensure atomicity.
请注意,get_or_create现在计划不推荐使用,因为MongoDB中没有事务支持,因此无法确保原子性。
The preferred way is update with upsert:
首选方法是使用upsert进行更新:
Location.objects(user_id=user_id).update_one(set__point=point, upsert=True)
More on upserts on the MongoDB documentation.
有关MongoDB文档的upsert的更多信息。
#2
5
this is what I came up with:
这就是我提出的:
location = Location.objects.get_or_create(user_id=user_id)[0]
location.point = point
location.save()
#3
2
There is a new way to do it since version 0.9 (explained here):
从版本0.9开始,有一种新的方法(在此解释):
location = Location.objects(user_id=user_id).modify(upsert=True, new=True, set__point=point)
It returns the created or updated object.
它返回创建或更新的对象。