如何做“插入如果不存在其他更新”用mongoengine? [英] How to do "insert if not exist else update" with mongoengine?

查看:487
本文介绍了如何做“插入如果不存在其他更新”用mongoengine?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆