Mongoengine:如何更新现有文档的特定字段?
Mongoengine : How to update specific fields of an existing document?
我有一个现有的 mongo 文档,该文档已通过 REST API 公开。 API 请求将包含文档中的某些字段,如果该字段为空,则需要使用新值更新或在其中插入新值。如何对现有 mongo 引擎文档的字段执行更新?我正在使用棉花糖-mongo引擎在烧瓶上进行序列化。
我面临的问题是,如果请求有效负载中缺少某个字段,则在使用剩余字段调用更新时,kwargs 会导致将缺少的字段设置为 None。如何仅更新或插入有效负载中给定的字段?
如果您只想更新一个文档,您可以使用保存方法。我就是做这个的。如果文档已经存在,它会更新字段而不是创建新文档。
car = Car.objects(pk=car_id) # return a queryset
if car:
car = car.get(pk=car_id) # return an object from queryset
car.make = requestData['make']
car.model = requestData['model']
car.mileage = requestData['mileage']
car.save()
如果您想更新很多文档,我建议您查看用户指南的 atomic updates 部分。
有点像~
Car.objects(param="param to filter by").update(set__param=newParam)
"set"后跟两个下划线是修饰符。我在上面链接的指南中提供了更多修饰符。
约瑟夫的回答是好的。但另一个答案不会伤害呃!
下面是我如何使用 flask-mongoengine 更新我的文档
实际代码:
Game.objects(id = _id).update(
set__kickoff = request_json.get('kickoff'),
set__gameid = request_json.get('gameid'),
set__home_team = request_json.get('home_team'),
set__away_team = request_json.get('away_team'),
set__home_win = request_json.get('home_win'),
set__draw = request_json.get('draw'),
set__away_win = request_json.get('away_win'),
set__sport = request_json.get('sport')
)
Game class :
import datetime
flask_mongoengine import BaseQuerySet, MongoEngine
db = MongoEngine()
class Game(db.Document):
kickoff = db.DateTimeField(required=True)
added_on = db.DateTimeField(default=datetime.datetime.utcnow)
gameid = db.FloatField(required=True)
home_team = db.StringField(required=True)
home_win = db.FloatField(required=True)
draw = db.FloatField(required=True)
away_win = db.FloatField(required=True)
away_team = db.StringField(required=True)
sport = db.StringField(required=True)
meta = {
'collection':'games',
'queryset_class': BaseQuerySet
}
PS : 记得在 python
中缩进代码
此外,我注意到您在问题中标记了 Marshmallow。在这里,来自他们官方 git repo here
的示例
First we need a Mongoengine Document:
import mongoengine as me
class Task(me.EmbeddedDocument):
content = me.StringField(required=True)
priority = me.IntField(default=1)
class User(me.Document):
name = me.StringField()
password = me.StringField(required=True)
email = me.StringField()
tasks = me.ListField(me.EmbeddedDocumentField(Task))
Great ! Now it's time for the Marshmallow Schema. To keep things DRY, we use marshmallow-mongoengine to do the mapping:
import marshmallow_mongoengine as ma
class UserSchema(ma.ModelSchema):
class Meta:
model = User
Finally it's time to use our schema to load/dump documents:First let's create a document
user_schema = UserSchema()
u, errors = user_schema.load({"name": "John Doe", "email":
"jdoe@example.com", "password": "123456","tasks": [{"content": "Find a
proper password"}]})
u.save()
If the document already exists, we can update it using update
u
u2, errors = user_schema.update(u, {"name": "Jacques Faite"})
>>> u2.name
"Jacques Faite"
我有一个现有的 mongo 文档,该文档已通过 REST API 公开。 API 请求将包含文档中的某些字段,如果该字段为空,则需要使用新值更新或在其中插入新值。如何对现有 mongo 引擎文档的字段执行更新?我正在使用棉花糖-mongo引擎在烧瓶上进行序列化。
我面临的问题是,如果请求有效负载中缺少某个字段,则在使用剩余字段调用更新时,kwargs 会导致将缺少的字段设置为 None。如何仅更新或插入有效负载中给定的字段?
如果您只想更新一个文档,您可以使用保存方法。我就是做这个的。如果文档已经存在,它会更新字段而不是创建新文档。
car = Car.objects(pk=car_id) # return a queryset
if car:
car = car.get(pk=car_id) # return an object from queryset
car.make = requestData['make']
car.model = requestData['model']
car.mileage = requestData['mileage']
car.save()
如果您想更新很多文档,我建议您查看用户指南的 atomic updates 部分。
有点像~
Car.objects(param="param to filter by").update(set__param=newParam)
"set"后跟两个下划线是修饰符。我在上面链接的指南中提供了更多修饰符。
约瑟夫的回答是好的。但另一个答案不会伤害呃!
下面是我如何使用 flask-mongoengine 更新我的文档
实际代码:
Game.objects(id = _id).update(
set__kickoff = request_json.get('kickoff'),
set__gameid = request_json.get('gameid'),
set__home_team = request_json.get('home_team'),
set__away_team = request_json.get('away_team'),
set__home_win = request_json.get('home_win'),
set__draw = request_json.get('draw'),
set__away_win = request_json.get('away_win'),
set__sport = request_json.get('sport')
)
Game class :
import datetime
flask_mongoengine import BaseQuerySet, MongoEngine
db = MongoEngine()
class Game(db.Document):
kickoff = db.DateTimeField(required=True)
added_on = db.DateTimeField(default=datetime.datetime.utcnow)
gameid = db.FloatField(required=True)
home_team = db.StringField(required=True)
home_win = db.FloatField(required=True)
draw = db.FloatField(required=True)
away_win = db.FloatField(required=True)
away_team = db.StringField(required=True)
sport = db.StringField(required=True)
meta = {
'collection':'games',
'queryset_class': BaseQuerySet
}
PS : 记得在 python
中缩进代码此外,我注意到您在问题中标记了 Marshmallow。在这里,来自他们官方 git repo here
的示例First we need a Mongoengine Document:
import mongoengine as me
class Task(me.EmbeddedDocument):
content = me.StringField(required=True)
priority = me.IntField(default=1)
class User(me.Document):
name = me.StringField()
password = me.StringField(required=True)
email = me.StringField()
tasks = me.ListField(me.EmbeddedDocumentField(Task))
Great ! Now it's time for the Marshmallow Schema. To keep things DRY, we use marshmallow-mongoengine to do the mapping:
import marshmallow_mongoengine as ma
class UserSchema(ma.ModelSchema):
class Meta:
model = User
Finally it's time to use our schema to load/dump documents:First let's create a document
user_schema = UserSchema()
u, errors = user_schema.load({"name": "John Doe", "email":
"jdoe@example.com", "password": "123456","tasks": [{"content": "Find a
proper password"}]})
u.save()
If the document already exists, we can update it using update
u
u2, errors = user_schema.update(u, {"name": "Jacques Faite"})
>>> u2.name
"Jacques Faite"